Skip to content Skip to sidebar Skip to footer

Jest: How To Get Arguments Passed To Mock Constructor?

If I want to create a mock implementation of an instance method of an ES6 Class I would do this // ExampleClass.js export class ExampleClass { constructor(someValue) {

Solution 1:

ExampleClass is the constructor function and since the entire module is auto-mocked it is already set up as a mock function:

import {fooBar} from './OtherModule';
import {ExampleClass} from './ExampleClass';
jest.mock('./ExampleClass');

it('try to create a mock of ExampleClass', () => {
    ExampleClass.mockClear();

    fooBar();

    // to verify values for of instance method "exampleMethod" of ExampleClass instance
    expect(ExampleClass.mock.instances[0].exampleMethod.mock.calls.length).toBe(1);  // SUCCESS
    expect(ExampleClass.mock.instances[0].exampleMethod.mock.calls[0][0]).toBe("another value");  // SUCCESS

    // Verify values for **constructor** of ExampleClass
    expect(ExampleClass.mock.calls.length).toBe(1);  // SUCCESS
    expect(ExampleClass.mock.calls[0][0]).toBe("hello world");  // SUCCESS
});

Post a Comment for "Jest: How To Get Arguments Passed To Mock Constructor?"