本文介绍了如何在 JEST 测试用例中检查来自全局获取的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在使用 jest 来测试我的节点函数,该函数调用 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.

谁能帮我解决问题?

推荐答案

.resolves 只能与 Promise 一起使用.

.resolves can only be used with a Promise.

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

global.fetch is a function so Jest throws an error.

如果您尝试断言通过调用 global.fetch 返回的 Promise 解析为具有返回 json 函数的对象code>{ data: 'hello' } 那么你可以这样做:

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 测试用例中检查来自全局获取的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 21:14