我是Jest的新手,我已经完成了对项目所有组件的测试,现在当我想测试axios调用时,我面临着这个错误。
我的测试
import addPatients from '../ApiCalls/ApiCalls'
test('patient data is posted', () => {
addPatients(data).then(response=>{
console.log(response.data)
})
});
Api.js
export function addPatients (state){
console.log(state)
try {
const response = axios.post('/addpatient', state);
// add patient calls rails controller, basically I'm using react on rails
console.log(response);
return response;
}
catch (error) {
console.log(error);
}
};
该项目工作得非常好,但我无法测试。当我运行这个测试时,我得到以下错误信息
TypeError.ApiCalls.default)不是函数。(0 , _ApiCalls.default) 不是一个函数。
22 | test('patient data is posted', () => {
23 |
> 24 | addPatients(data).then(response=>{
| ^
25 | console.log(response.data)
26 |
27 | })
at Object.<anonymous> (app/javascript/components/__tests__/Api.test.js:24:5)
我试过用.NET Framework 2.0来实现。
试了几天,好像都不行。请指导我测试这个,因为唯一的工作是测试。
所以,首先,正如 @EstusFlask 在评论区指出的,我导入的方式不对。
改变了
import addPatients from '../ApiCalls/ApiCalls' to import {addPatients}
from '../ApiCalls/ApiCalls'
然后,我没有正确地模拟调用,我把代码和解释贴出来,以便对某些人有所帮助。
调用Api的函数
export function addPatients (state){
const response = axios.post('/addpatient', state);
return response;
};
测试案例
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter';
import {addPatients} from '../ApiCalls/ApiCalls'
const data ={
"patientage":"patientage",
"patientname":"test",
"patientgender":"patientgender",
"patientinsurance":"patientinsurance",
"patientphone":"patientphone",
"patientdiagnosis":"patientdiagnosis",
"patientaddreq":"patientaddreq",
"patientemr":"patientemr"
}
const mockresponse = {
Status:'200'
}
describe('addnewpatient', () => {
it('should post patient data', () => {
const mockRequest = new MockAdapter(axios);
mockRequest.onPost('/addpatient').reply(200,mockresponse);
return addPatients(data).then(response => expect(response.data.Status).toEqual('200'));
});
});
所以基本上mockrequest的作用是,每当addpatient函数调用api时,它就会调用我们创建的模拟axios请求和我们提供的数据,而不是调用实际的api。
在这种情况下,mock会在以下情况下进行拦截
稍后你可以将api函数接收到的数据和你用expect提供的模拟数据进行比较。在我的例子中,'addpatient'调用了rails控制器,URL可以是任何与你的项目相关的东西。