mercredi 27 mai 2020

jest mocking and setting up default behavior

There is a function I need to unit test:

const readiness = require("./readiness");

function stopProcessNewRequests(){
    readiness.setNotReady();
}

Here is my "readiness" file:

const state = require("./state");
const hooks = require("./hooks");

function setReady(){
    state.ready = true;
    hooks.notifyHook(state.ready);
}

function setNotReady(){
    state.ready = false;
    hooks.notifyHook(state.ready);
}

module.exports = {
    setReady, setNotReady
};

and finally, the state.js file:


exports.ready = false;

exports.pendingRequests = {};

exports.changeStatusHooks = [];

exports.requestsInProcessNum = 0;

exports.authClient = null;
exports.webOperationsClient = null;
exports.webQueryClient = null;

As you can see, there are multiple chained imports, how do I mock them? I need my state file to be of certain values in order to check if it actually changes. Here's what I have, but state does not seem to change, and the test fails.

describe('Testing processing new requests:', ()=> {
        test('should stop processing new requests:', ()=> {
            // jest.mock('../lib/grpc/readiness',);
            jest.mock('../lib/grpc/state');

            const state = require("../lib/grpc/state");
            const { stopProcessNewRequests } = require('../lib/grpc/requestsManager');

            state.ready = true;

            stopProcessNewRequests();

            expect(state.ready).toBeFalsy();
        })
    })

Aucun commentaire:

Enregistrer un commentaire