class function call in jest code example
Example 1: jest mock instance
test("mock.instances", () => {
const mockFn = jest.fn();
const a = new mockFn();
const b = new mockFn();
mockFn.mock.instances[0] === a;
mockFn.mock.instances[1] === b;
});
Example 2: jest spy on class method
class MyClass {
methodOne() {
return 1;
}
methodTwo() {
return 2;
}
}
module.exports = MyClass;
test('spy using class method', () => {
const result = new MyClass()
const spy = jest.spyOn(result, 'methodOne')
result.methodOne()
expect(spy).toHaveBeenCalled()
expect(result.methodOne()).toBe(1)
spy.mockReturnValueOnce(12)
expect(result.methodOne()).toBe(12)
})