开玩笑:如何获取传递给模拟构造函数的参数? [英] Jest: How to get arguments passed to mock constructor?
本文介绍了开玩笑:如何获取传递给模拟构造函数的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我想创建ES6类实例方法的模拟实现,
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! ❤
推荐答案
ExampleClass
是构造函数,由于整个模块都是自动模拟的,因此已经将其设置为模拟函数:
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
});
这篇关于开玩笑:如何获取传递给模拟构造函数的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文