如何在 JEST 中的 express 中间件中测试 next()

vai*_*hav 3 unit-testing node.js express jestjs

经过很多努力,我无法弄清楚这一点,因此计划寻求帮助。我在我的 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(() => {
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

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

我写的测试用例是:

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.
    });
});
Run Code Online (Sandbox Code Playgroud)

mga*_*cia 6

您必须等待中间件解析。当您从中间件返回承诺时,您可以在测试中使用以下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.
    });
});
Run Code Online (Sandbox Code Playgroud)

请注意,为了能够使用await关键字,您需要使用async.