问题
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) {
this.a = someValue;
}
exampleMethod(anotherValue) {
// do something with 'anotherValue'
}
}
// OtherModule.js
import {ExampleClass} from './ExampleClass';
export const fooBar = () => {
const ex = new ExampleClass("hello world");
ex.exampleMethod("another value");
};
// ExampleClass.test.js
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.calls.length).toBe(1);
expect(ExampleClass.mock.instances[0].exampleMethod.calls[0][0]).toBe("another value");
// How to verify values for **constructor** of ExampleClass ?????
// expect(ExampleClass.mock.instances[0].constructor.calls.length).toBe(1);
// expect(ExampleClass.mock.instances[0].constructor.calls[0][0]).toBe("another value");
});
What I don't know how to do (and sort of alluded to in the commented code) is how to spy on / access the values of the constructor (not just an instance method).
Any help would be greatly appreciated! ❤
回答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
});
来源:https://stackoverflow.com/questions/54384793/jest-how-to-get-arguments-passed-to-mock-constructor