我的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()
})
})
需要
我希望当我测试第二个测试时,jest用一个新值呈现Companies页面,实际上,这个值是一个空数组([])。
我尝试使用新的api
模拟重新呈现it
函数内的组件。
我想在我的第二个测试中实现一个特定的结果。
1条答案
按热度按时间f45qwnt81#
我用
jest-mock-axios
解决了问题