Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock new Function() with Jest

I'm having trouble trying to mock a module with a constructor

// code.js
const ServiceClass = require('service-library');
const serviceInstance = new ServiceClass('some param');
exports.myFunction = () => {
  serviceInstance.doSomething();
};

And the test code:

// code.test.js
const ServiceClass = require('service-library');
jest.mock('service-library');
const {myFunction} = require('../path/to/my/code');

test('check that the service does something', () => {
  // ????
});

It's not like the Documentation example Mocking Modules because you need to instantiate the module after importing it. And isn't either like Mocking a Function.

How could I mock this doSomething() function while testing?

For reference, I'm trying to mock @google-cloud/* packages here. And I have a few projects that could take advantage on this.

like image 677
dinigo Avatar asked Oct 17 '18 16:10

dinigo


People also ask

How do you call a mock function in Jest?

You can create a namespace that you export as the default object and call b using the namespace. This way, when you call jest. mock it will replace the b function on the namespace object. const f = require('./f'); jest.

How do you mock a function in Jest React?

Let's refactor the test to use this approach: test("Should render character name", async () => { const mock = jest. spyOn(data, "getCharacter"). mockResolvedValue("Bob"); render(<Hello id={1} />); expect(await screen.

What is the Jest fn () in Jest?

The jest. fn method allows us to create a new mock function directly. If you are mocking an object method, you can use jest.

How do you mock a function in class Jest?

In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). Since calls to jest. mock() are hoisted to the top of the file, Jest prevents access to out-of-scope variables.


1 Answers

You need to mock the whole module first so that returns a jest mock. Then import into your test and set the mock to a function that returns an object holding the spy for doSomething. For the test there is difference between of a class called with new and a function called with new.

import ServiceLibrary from 'service-library'

jest.mock( 'service-library', () => jest.fn())

const doSomething = jest.fn()
ServiceLibrary.mockImplementation(() => ({doSomething}))
like image 68
Andreas Köberle Avatar answered Sep 23 '22 17:09

Andreas Köberle