export class Foo { public static bar() { doSomething(); } constructor(paramA, paramB) { } }
For a method in a class, we can use jest.spyOn(Foo, 'bar')
to spy on the method. How about constructor? How do we spy how the object is instantiated?
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.
To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.
With Jest's automatic mocks, we can mock classes or constructor functions easily. All methods are mocked with functions that return undefined . Then we can retrieve the mock by using mockedObject. mock. instances , which is an array.
The jest. fn method is, by itself, a higher-order function. It's a factory method that creates new, unused mock functions. Also, as we discussed previously, functions in JavaScript are first-class citizens. Each mock function has some special properties.
@gillyb is right just forgot to "mock" the Foo module
// Foo.js export class Foo { public static bar() { doSomething(); } constructor(paramA, paramB) { } } // Foo.spec.js import Foo from './Foo.js'; jest.mock('./Foo.js'); it('test something...', () => { // Assuming we did something that called our constructor expect(Foo).toHaveBeenCalledTimes(1); });
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