Function is not calling mocked constructor in Jest test


I have a setup similar to this question but the partial mocking answer is not working for me.

I have a file ‘FiscalYear.jsx’ which contains a class FiscalYear and a few related non-class functions eg

export class FiscalYear {
    constructor(fy) { //does stuff }
    // other functionality
}

export function getFY(offset) {
    // does stuff
    return new FiscalYear(fy);
}

I want my Jest test for the getFY function to simply check that the FiscalYear constructor was called with the right parameter. I used partial mocking in my test file to accomplish this:

import { FiscalYear, getFY } from '../FiscalYear';

jest.mock('../FiscalYear', () => {
    const originalModule = require.requireActual('../FiscalYear');
   
    return {
        ...originalModule,
        FiscalYear: jest.fn().mockImplementation((a) => { })
    };
});

test("getFY", () => {
    getFY(2);
    expect(FiscalYear).toHaveBeenCalled();
});

I’ll update the toHaveBeenCalled to toBeCalledWith once I make it actually call the function. However currently the test fails with

expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

I put a console.log in the real constructor and confirmed that the getFY function is calling that instead of the mock constructor.

How to get this working? Is it a bad design to have these both in the same file? Totally new to JavaScript so if this is bad practice please let me know.

Source: React – Stack Overflow

October 1, 2021
Category : News
Tags: javascript | jestjs | mocking | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.