【问题标题】:How to test next() in express middleware in JEST如何在 JEST 的 express 中间件中测试 next()
【发布时间】:2019-10-02 06:12:43
【问题描述】:

经过大量努力,我无法弄清楚这一点,因此计划寻求帮助。我在我的 node+ express 应用程序中使用了一个中间件,它看起来像:

import mainConfig from '../mainConfig/index';
const axios = require('axios');

module.exports = {
    authHandler: (req, res, next) => {
        return mainConfig.initialize().then(() => {
            const apiUri = mainConfig.get('app.api');
            if (apiUri) {
                return axios.get(apiUri).then(response => {
                    next();
                }).catch(error => {
                    res.redirect('/expired');
                    throw new Error(error);
                });
            }
        }).catch(() => {
        });
    }
};

为此,我编写了能够模拟 axios 和我的 mainCongig 模块的测试用例。现在,我想测试是否在为 axios 解析请求时调用了 next()。有人可以帮助我吗?

我写的测试用例是:

import mainConfig from '../mainConfig';
const axios = require('axios');

const middlewares = require('./check-auth');
jest.mock('axios');

describe('Check-Auth Token', () => {
    it('should call the Sign In API when live Conf is initalized and have the API URL', () => {

        mainConfig.get = jest.fn();
        mainConfig.get.mockReturnValue('https://reqres.in/api/users');
        mainConfig.initialize = jest.fn(() => Promise.resolve({ data: {} }));
        const req = jest.fn(), res = { sendStatus: jest.fn() }, next = jest.fn();
        axios.get.mockImplementation(() => Promise.resolve({ data: {} }));
        middlewares.authHandler(req, res, next);
        expect(next).toHaveBeenCalled(); // coming as not called.
    });
});

【问题讨论】:

  • 您能否确保您的 authHandler 可以正常使用您的模拟?将调试点添加到您的 authHandler 并再次运行测试,在 next(); 行之前附加 console.log('next has been called');

标签: node.js unit-testing express jestjs


【解决方案1】:

我不是专家,但据我所知,您正在测试异步代码。所以你必须使用done() 关键字。查找更多信息:https://jestjs.io/docs/en/asynchronous

【讨论】:

    【解决方案2】:

    您必须等待中间件解析。当您从中间件返回一个 Promise 时,您可以使用 await 语句在测试中等待:

    import mainConfig from '../mainConfig';
    const axios = require('axios');
    
    const middlewares = require('./check-auth');
    jest.mock('axios');
    
    describe('Check-Auth Token', () => {
        it('should call the Sign In API when live Conf is initalized and have the API URL', async () => {
    
            mainConfig.get = jest.fn();
            mainConfig.get.mockReturnValue('https://reqres.in/api/users');
            mainConfig.initialize = jest.fn(() => Promise.resolve({ data: {} }));
            const req = jest.fn(), res = { sendStatus: jest.fn() }, next = jest.fn();
            axios.get.mockImplementation(() => Promise.resolve({ data: {} }));
            await middlewares.authHandler(req, res, next);
            expect(next).toHaveBeenCalled(); // coming as not called.
        });
    });
    

    请注意,为了能够使用 await 关键字,您需要使用 async 定义您的测试。

    【讨论】:

    • 非常感谢@mgarcia,这就像魅力一样。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 2022-01-15
    • 2017-12-25
    • 1970-01-01
    • 2013-08-22
    • 2021-10-23
    • 1970-01-01
    • 2021-04-29
    相关资源
    最近更新 更多