Mahyar
Mahyar

Reputation: 1121

Jest: Mock one function in a class

I'm very new to node and javascript, and trying to write a unittet with jest where I need to only mock 1 function of a class (and object).

Here's a template I'm using:

// myModule.js
class MyModule {
    constructor() {
      console.log("hello");
    }
    getCases(){
        return 2;
    }
    getOtherCases(){
        return 3;
    }
}
module.exports = MyModule;

and the test:

// myModule.test.js
jest.unmock('./myModule.js');
const myModule = require('./myModule.js');
myModule.getCases = jest.fn();

describe('Test mock function', () => {
    beforeAll(() => {
        myModule.getCases.mockImplementation(() => 32);
        mod = new myModule();
    });

    it('should pass', () => {
        console.log(mod.getCases());
        console.log(myModule.getCases());
    });
  });

The problem over here is mod.getCases() does not mock the function (myModule.getCases() does)

console.log myModule.test.js:12
2


console.log myModule.test.js:13
32

Is there a specific way I need to create the object so it would mock the function?

Upvotes: 0

Views: 1230

Answers (1)

Jack
Jack

Reputation: 804

You must replace all MyModule.getCases with MyModule.prototype.getCases.

This is because the class syntax is just syntactic sugar. Without this you would instead have (and indeed we used to do this).

function MyModule () {
    console.log('hello')
}

MyModule.prototype.getCases = function () {
    return 2;
};

MyModule.prototype.getOtherCases = function () {
    return 3;
};

module.exports = MyModule;

This is completely equivalent to your code and if you copied and pasted it you would see it worked in the same way.

As all objects created with new inherit the prototype, the above syntax is just a very manual way of creating shared functions for instances of objects. Prototypal inheritance can be quite confusing at first, and it took me a while to get it too, but you can read about it here, and this video is quite good also.

When you were performing myModule.getCases in your tests were not actually modifying the prototype property which your instance (created with new) would inherit.

Now seeing that getCases inside your class syntax and getCases on the prototype are the same thing, hopefully you can see why the replacement solves your problem.

If I haven't explained anything very clearly or you want me to clarify anything feel free to ask.

Upvotes: 2

Related Questions