模拟AxiosInstance.只想在一次测试中得到回报



我的api.ts文件

import axios from 'axios'
export const api = axios.create({
baseURL: 'http://localhost:3333/',
})

我的react-page.spec.tsx文件:

import React from 'react'
import '@testing-library/jest-dom'
import { act, cleanup, render, RenderResult } from '@testing-library/react'
import { Companies } from '../../../../modules/companies/pages/companies'
import { Company } from '../../../../@types/company.type'

let companiesPageElement: RenderResult
const companies: Company[] = [
{
_eq: 'id-company-1',
logo: 'https://s.yimg.com/ny/api/res/1.2/a19vkjSUoD4hVV0djOpSLw--/YXBwaWQ9aGlnaGxhbmRlcjt3PTEyMDA7aD02Nzc-/https://s.yimg.com/os/creatr-uploaded-images/2020-07/20e95610-d02d-11ea-9f0c-81042fd4c51a',
name: 'Casas Bahia',
manager: 'Daniel Ribeiro',
status: 'late'
}
]

const mockedAxiosGet = (...args: any) => jest.fn(...args).mockReturnValue({ data: companies })
jest.mock('../../../../api', () => {
return {
api: {
get: (...args: any) => {
return mockedAxiosGet(...args)()
}
}
}
})
describe('<Companies />', () => {
beforeEach(async () => {
await act(async () => {
companiesPageElement = render(<Companies />)
})
})
it('should be able to render correctly the page', async () => {
// It's a test that use the mockedAxiosGet as all other tests
})
it('should be able to go to Create first company page if no companies has found in database', async () => {
// It's the test that I want to change the api.get return value
})
afterEach(() => {
cleanup()
})
})
需要

我希望当我测试第二个测试时,该笑话用一个新值呈现Companies页面。实际上,该值是一个空数组([])。

我尝试用新的api模拟来渲染it函数中的组件。

我想为我的第二个测试实现一个特定的结果。

我用jest-mock-axios解决了这个问题

最新更新