如何在 JEST 测试用例中检查来自全局获取的响应

IT技术 node.js reactjs express jestjs
2021-05-15 23:57:05

所以,我正在使用 jest 来测试我的节点函数,该函数调用 fetch() APi 来获取数据,现在当我编写相同的测试用例时,我收到如下错误:

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,也不想使用。

任何人都可以帮助我解决问题吗?

1个回答

.resolves只能与Promise.

global.fetch是一个函数所以Jest抛出一个错误。

如果您尝试断言Promise通过调用返回global.fetch的对象解析为具有json返回函数的对象,{ data: 'hello' }那么您可以执行以下操作:

expect((await global.fetch()).json()).toEqual({ data: 'hello' });  // Success!

...但我怀疑你真的想验证它response.data存在并且res.redirect被调用,'somewhere'在这种情况下你的断言应该是这样的:

expect(res.redirect).toHaveBeenCalledWith('somewhere');  // Success!