Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy on a class constructor jest?

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?

like image 237
Jonathan Tse Avatar asked Jan 12 '18 03:01

Jonathan Tse


People also ask

How do you mock a constructor in 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.

How do you spy on module Jest?

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.

What is auto mocking in 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.

What is Jest FN?

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.


1 Answers

@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); }); 
like image 87
N4N0 Avatar answered Sep 19 '22 11:09

N4N0