简体   繁体   中英

How to test next() in express middleware in JEST

After a lot of efforts i was not able to figure this one out and hence planned to get the help. I am using a middleware in my node+ express app which looks like :

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(() => {
        });
    }
};

For this, I have written the test case in which I was able to mock the axios and my mainCongig module. Now, I want to test whether next() was called as the request was resolved for axios. Can someone help me with the same?

test case I have written is :

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.
    });
});

I'm not an expert, but as far as I know you are testing asynchronous code. So you have to use the done() keyword. Lookup this for more information: https://jestjs.io/docs/en/asynchronous

You have to wait for the middleware to resolve. As you are returning a promise from your middleware, you can wait in the test with an await statement:

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.
    });
});

Note that in order to be able to use the await keyword you need to define your test with async .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM