我是第一个用Jest编写第一个测试用例的新手。我得模拟一个回音。我用的是取笑-取笑-模仿。但是,调用将转到实际的fetch,并且返回的数据未定义。
package.json:
“嘲笑-获取-模拟”:"^2.1.2“
setupTest.js文件
global.fetch = require('jest-fetch-mock');实际api调用方法:
static fetchUserInfo(){
return dispatch => {
fetch('https://localhost:55001/api/userInfo')
.then(this.httpResponseHandler.handleHttpResponse)
.then ((resp) => resp.json())
.then(data => dispatch(this.onUserInfoGetSuccess(data)))
.catch( error => {
dispatch(this.onFetchFailure(error));
});
};
}测试用例
it('should get user info', () => {
fetch.mockResponse(JSON.stringify({
"name": "swati joshi",
}
));
let data = ActualDataApi.fetchUserInfo();
console.log(data);
expect(data.name).toEqual('swati joshi');
}既然fetchUserInfo是dispatcher (使用React),那么如何模拟它呢?提前谢谢!
发布于 2019-06-11 17:07:08
有可能fetch没有被模仿,correctly...but看起来最主要的问题是fetchUserInfo返回一个函数。
应该在dispatch模拟上调用它返回的函数,以验证它是否分派了正确的操作。
还请注意,fetchUserInfo返回的函数是异步的,因此您需要一种方法来等待它在测试期间完成。
如果您修改fetchUserInfo返回的函数以返回Promise,如下所示:
static fetchUserInfo(){
return dispatch => {
return fetch('https://localhost:55001/api/userInfo') // <= return the Promise
.then(this.httpResponseHandler.handleHttpResponse)
.then((resp) => resp.json())
.then(data => dispatch(this.onUserInfoGetSuccess(data)))
.catch(error => {
dispatch(this.onFetchFailure(error));
});
};
}...then您可以这样测试它:
it('should get user info', async () => { // <= async test function
fetch.mockResponse(JSON.stringify({
"name": "swati joshi",
}));
let func = ActualDataApi.fetchUserInfo(); // <= get the function returned by fetchUserInfo
const dispatch = jest.fn();
await func(dispatch); // <= await the Promise returned by the function
expect(dispatch).toHaveBeenCalledWith(/* ...the expected action... */);
});https://stackoverflow.com/questions/56520314
复制相似问题