robben bahati
robben bahati

Reputation: 19

Testing javascript closures in jest

I have a code pattern like this. I need to test the underlying functions func1, and func2. In Func2, I am making call to func1, I need to spy or mock func1 and check if it has been called. However, my test cases seem to be calling the actual function instead of a spy or a mock. please help.

function init() {
    const func1 = () => {
        // Some implementation
    };

    const func2 = () => {
        // Call func1
        func1();
    };

    return { func1, func2 };
}

module.exports = { init };

This is the format of my test cases

const { init } = require('./path_to_your_module');

describe('func2', () => {
    it('should call func1 without invoking its implementation', () => {
        // Get the functions from init
        const { func1, func2 } = init();

        // Mock func1
        const mockFunc1 = jest.fn();
        func1 = mockFunc1; // Replace func1 with the mock in the scope of this test

        // Call func2
        func2();

        // Assert func1 was called
        expect(mockFunc1).toHaveBeenCalledTimes(1);
    });

    it('should spy on func1 without calling the actual implementation', () => {
        // Get the functions from init
        const { func1, func2 } = init();

        // Spy on func1
        const spyFunc1 = jest.spyOn({ func1 }, 'func1').mockImplementation(() => {});

        // Call func2
        func2();

        // Assert func1 was called
        expect(spyFunc1).toHaveBeenCalled();

        // Clean up the spy
        spyFunc1.mockRestore();
    });
});

Upvotes: 0

Views: 23

Answers (0)

Related Questions