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

5

经过许多努力,我仍然无法解决这个问题,因此打算寻求帮助。 我正在使用一个中间件在我的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和我的mainConfig模块。现在,我想测试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'); - hoangdv
2个回答

9

您需要等待中间件解决。由于您从中间件返回了一个承诺,因此您可以在测试中使用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,这个运行得很好。 :) - vaibhav

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接