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

时间:2019-05-15 07:16:29

标签: node.js unit-testing 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(() => {
        });
    }
};

为此,我编写了一个测试案例,可以模拟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.
    });
});

2 个答案:

答案 0 :(得分:1)

您必须等待中间件解决。当您从中间件返回承诺时,可以使用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定义测试。

答案 1 :(得分:0)

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