How to check the response from global fetch in JEST test case

自闭症网瘾萝莉.ら 提交于 2021-02-10 14:18:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!