Jest Mock未按预期工作抛出错误


const axios = "axios";
jest.mock(axios);
axios.get.mockImplementation((url) => {
if(url === process.env.ENHANCED_CLAIM_STATUS_276_DETAILS){
return Promise.resolve({ status: 200, data: claim_response_276 });
}
if(url === process.env.ENHANCED_VALUE_ADDS_277_DETAILS){
return Promise.resolve({ status: 200, data: claim_response_277 });
}
});

我试图模拟API响应,但它抛出这个错误:

**TypeError: Cannot read properties of undefined (reading 'mockImplementation')**

moduleName参数应该是字符串. 参见API文档。mock(moduleName, factory, options)

工作示例:

import axios from "axios";
jest.mock('axios');
describe('74929332', () => {
test('should pass', async () => {
axios.get.mockImplementation((url) => {
return Promise.resolve({ status: 200, data: 'claim_response_276' });
});
const result = await axios.get('http://localhost:3000/api')
expect(result).toEqual({ status: 200, data: 'claim_response_276' })
})
});

测试结果:

PASS  stackoverflow/74929332/index.test.js (14.419 s)
74929332
✓ should pass (3 ms)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.559 s

最新更新