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.
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.
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.
The jest. fn method allows us to create a new mock function directly. If you are mocking an object method, you can use 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.
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}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With