我从jest-fetch-模拟npm包示例中获取了确切的代码示例,我不能让它失败。有人能告诉我我做错了什么吗?
这是我的密码:
require('jest-fetch-mock').enableMocks();
const APIRequest = (who) => {
if (who === 'google') {
return fetch('https://google.com').then((res) => res.json());
} else {
return 'no argument provided';
}
};
describe('testing api', () => {
beforeEach(() => {
fetch.resetMocks();
});
it('calls google and returns data to me', () => {
fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));
//assert on the response
APIRequest('google').then((res) => {
expect(res.data).toEqual('not 12345');
});
});
});即使,很明显,我对fetch的模拟响应与我预期的结果不匹配,但jest仍然说测试通过了,为什么?它告诉我,在“测试通过”部分上,它收到了比预期更多的东西,但是测试仍然显示“通过”,为什么?我怎样才能让它在这种情况下失败,在这种情况下它是如何被期望的。
发布于 2021-04-15 07:32:10
对您的问题有两种可能的解决方案:
expect.assertions来开玩笑,验证是否所有断言都被断言为,并返回一个expect.assertions it('calls google and returns data to me', () => {
fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));
expect.assertions(1);
//assert on the response
return APIRequest('google').then((res) => {
expect(res.data).toEqual('not 12345');
});
});
});如果您返回承诺,jest将知道代码运行异步。
使用async/await语法:
it('calls google and returns data to me', async () => {
fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));
expect.assertions(1);
//assert on the response
const result = await APIRequest('google')
expect(result).toEqual('not 12345');
});
});https://stackoverflow.com/questions/67104029
复制相似问题