在Jest Test中没有调用Res.Redirect

时间:2019-05-22 10:18:54

标签: node.js unit-testing express jestjs

我正在使用node-express,并尝试从API调用成功时检查重定向。我收到一个错误消息-Expected mock function to have been called, but it was not called.

这是我的功能:

export function globalAuthHandler (req, res, next) {
    const global_signin_url = config.get('url');
    if (global_signin_url) {
        console.log(global_signin_url);
        fetch(global_signin_url)
            .then((response) => response.json())
            .then((response) => {
                console.log('Response', response);
                if (response.data) {
                    console.log('Success!!!');
                    res.redirect('/signIn');
                } else {
                    console.log('going here 1' + response);
                    res.redirect('/session-expired');
                    throw Error(response.statusText);
                }
            })
            .catch((error) => {
                console.log('going global here 2 ' + error);
                next(error);
            });
    } else {
        console.log('going here 3');
        res.redirect('/session-expired');
    }
}

这是测试:

it('should throw the error and redirect if the API fails with 404.', async () => {
        // Setup
        Config.get = jest.fn();
        Config.get.mockReturnValue(true);
        Config.initialize = jest.fn(() => Promise.resolve({ data: {} }));
        const req = jest.fn(),
            res = { redirect: jest.fn() },
            next = jest.fn();
        //global.fetch = jest.fn(() => new Promise((resolve) => resolve({ response: { ok: false, status: 404 } })));
        global.fetch = jest.fn(
            () =>
                new Promise((resolve) =>
                    resolve({
                        json: () => {
                            return { };
                        }
                        /* data: { ok: true } */
                    })
                )
        );

        // Act
        await middlewares.globalAuthHandler(req, res, next);
        //  Assert
        expect(res.redirect).toHaveBeenCalled();
        expect(res.redirect).toHaveBeenCalledWith('/signIn');
    });

我无法弄清楚-即使进入success!!!日志之后,重定向也没有被触发。

1 个答案:

答案 0 :(得分:1)

'97 98 99' 上调用await不会等待其完成,因为它没有返回middlewares.globalAuthHandler

返回Promise创建的Promise

fetch

...并且测试将等待export function globalAuthHandler (req, res, next) { ... return fetch(global_signin_url) // <= return the Promise ... } 解析,然后继续执行Promise语句。

这将为expect提供一个在测试之前被调用的机会。