问题描述
所以,我正在用玩笑来测试我的调用fetch()APi来获取数据的节点函数,现在当我为相同的示例编写测试用例时,出现了类似
So, i am using jest for testing my node function which is calling fetch() APi to get the data, now when I am writing the test cases for the same i am getting an error like :
expect(received).resolves.toEqual()
Matcher error: received value must be a promise
Received has type: function
Received has value: [Function mockConstructor]
我的功能:
export function dataHandler (req, res, next) {
const url= "someURL"
if (url ) {
return fetch(url )
.then((response) => response.json())
.then((response) => {
if (response.data) {
console.log(response);
res.redirect(somewhere`);
} else {
throw Error(response.statusText);
}
})
.catch((error) => {
next(error);
});
}
}
测试用例:
it('check if fetch returning the response', async () => {
// Setup
const req = jest.fn(),
res = { redirect: jest.fn() },
next = jest.fn();
global.fetch = jest.fn().mockImplementation(() => {
return new Promise((resolve) =>
resolve({
json: () => {
return { data: "hello"};
}
})
);
});
await middlewares.dataHandler(req, res, next);
// Assert
expect(global.fetch).resolves.toEqual({ data: "hello" });
});
请注意,我没有使用任何模拟API,并且宁愿不使用.
Please be advised I am not using any mocking API, and would prefer not to.
有人可以帮助我解决问题吗?
Can anyone help me with what's going wrong?
推荐答案
.resolves
仅可与Promise
一起使用.
global.fetch
是一个函数,因此Jest
会引发错误.
global.fetch
is a function so Jest
throws an error.
如果您试图断言通过调用global.fetch
返回的Promise
解析为带有返回{ data: 'hello' }
的json
函数的对象,则可以执行以下操作:
If you are trying to assert that the Promise
returned by calling global.fetch
resolves to an object with a json
function that returns { data: 'hello' }
then you can do this:
expect((await global.fetch()).json()).toEqual({ data: 'hello' }); // Success!
...但是我怀疑您确实是在尝试验证response.data
是否存在,并且res.redirect
是用'somewhere'
调用的,在这种情况下,您的主张应该只是这样:
...but I suspect that you are really trying to verify that response.data
existed and that res.redirect
was called with 'somewhere'
in which case your assertion should just be this:
expect(res.redirect).toHaveBeenCalledWith('somewhere'); // Success!
这篇关于如何在JEST测试用例中检查全局获取的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!