问题
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]
my function :
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);
});
}
}
testcase :
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" });
});
Please be advised I am not using any mocking API, and would prefer not to.
Can anyone help me with what's going wrong?
回答1:
.resolves
can only be used with a Promise
.
global.fetch
is a function so Jest
throws an error.
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!
...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!
来源:https://stackoverflow.com/questions/56355434/how-to-check-the-response-from-global-fetch-in-jest-test-case