lundi 23 novembre 2020

Jest mock the required statements

I have the following file i want to test:

const cachedResult = require('../middleware/cached-result.js');
const protect = require('../middleware/auth.js');
const { addMiddleware } = require('./helpers.js');

const binder = (app, routes) => {
    for (const route of routes) {
        let args = [route.path, route.handler];
        if (route?.protected) args = addMiddleware(args, protect(route?.protected?.roles));
        if (route?.cachedResult) args = addMiddleware(args, cachedResult(route?.cachedResult));
        app[route.method.toLowerCase()](...args);
    }
    return app;
};

module.exports = binder;

Here's the spec file:

const httpBinder = require('../../../src/utils/http-binder');

describe('tests', () => {
    it('Should bind a route to app.', () => {
        const routes = [
            {
                path: '/users',
                method: 'GET',
                handler: () => {}
            }
        ];
        const app = {
            get: (...args) => args
        };
        const appWithRoutes = httpBinder.bind(app, routes);
        expect(appWithRoutes).toHaveProperty('get');
    });
});

The test passed successfully, but the problems here that it marks the follwong files as tested too:

const cachedResult = require('../middleware/cached-result.js');
const protect = require('../middleware/auth.js');
const { addMiddleware } = require('./helpers.js');

Even worst it open the redis connection because of this file: require('../middleware/cached-result.js');

Is there any way I can mock the required statements as to functions or something like that?

Aucun commentaire:

Enregistrer un commentaire