
[英]TypeError: (0 , _axios.default) is not a function when use jest.mock('axios') inside a *.test.js file
[英]2 different instance of axios mock having returning an error of axios.default is not a function
在我的 function 中命名为 eventController。 axios 调用以两种方式实现第一种是在此代码上
axios.post(
`${url}/API1`,
{
data:'data for API1'
}
)
那么这是第2
await axios({
method: 'POST',
url: `${url}/API2`,
data: {
data:'data for API2'
}
})
一个函数/控制器中有 2 个不同的 axios 调用
我被分配在 typescript 中使用 jest 对此进行单元测试
所以我到目前为止所做的是
jest.mock('axios', () => ({
post: jest
.fn()
.mockResolvedValueOnce({ status: 200 })
}));
it("should work", async () => {
const req = {body: {
data: 'data for API'
}}
const response = await eventController(req);
expect(response.status).toBe(200);
});
我模拟了第一个 axios 调用 with.post 方法,但是当使用默认的 axios 模块进行第二个调用时,我收到了这个错误
TypeError: (0 , axios_1.default) is not a function
我也尝试过以这种方式实现,但两者似乎都不起作用:
jest.mock('axios', () => ({
__esModule: true,
default: jest.fn(),
post: jest
.fn()
.mockResolvedValueOnce({ status: 200 })
}));
和这个:
jest.mock('axios', () => ({
__esModule: true,
default: {
post: jest
.fn()
.mockResolvedValueOnce({ status: 200 })
},
}));
希望有人可以帮助我解决这个问题。 这是我当前使用的库的版本
只需使用jest.mock(moduleName, factory, options)
并且不传递factory
参数,让 jest 模拟具有自动模拟版本的模块。 而且,没有__mocks__
目录。
您需要在axios
function 和axios.get()
方法的 TS 类型,使用类型转换来执行此操作。
注意:我使用一个简单的字符串作为模拟解析值,它与AxiosResponse
接口不匹配。
例如
main.ts
:
import axios from 'axios';
const url = 'http://localhost:3000';
export async function main() {
const res1 = await axios.post(`${url}/API1`, {
data: 'data for API1',
});
console.log('res1: ', res1);
const res2 = await axios({
method: 'POST',
url: `${url}/API2`,
data: {
data: 'data for API2',
},
});
console.log('res2: ', res2);
}
main.test.ts
:
import { main } from './main';
import axios from 'axios';
jest.mock('axios');
const axiosMock = axios as jest.MockedFunction<typeof axios>;
const axiosPostMock = axios.post as jest.MockedFunction<typeof axios.post>;
test('should pass', async () => {
expect(jest.isMockFunction(axios)).toBe(true);
expect(jest.isMockFunction(axios.post)).toBe(true);
axiosPostMock.mockResolvedValueOnce('fake data 1');
axiosMock.mockResolvedValueOnce('fake data 2' as any);
await main();
});
测试结果:
PASS stackoverflow/76407602/main.test.ts (38.236 s)
✓ should pass (48 ms)
console.log
res1: fake data 1
at stackoverflow/76407602/main.ts:8:11
console.log
res2: fake data 2
at stackoverflow/76407602/main.ts:16:11
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 41.384 s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.