如果我想创建 ES6 类的实例方法的模拟实现,我会这样做
\n\n// ExampleClass.js\nexport class ExampleClass {\n constructor(someValue) {\n this.a = someValue;\n }\n\n exampleMethod(anotherValue) {\n // do something with \'anotherValue\'\n }\n}\n\n// OtherModule.js\nimport {ExampleClass} from \'./ExampleClass\';\nexport const fooBar = () => {\n const ex = new ExampleClass("hello world");\n ex.exampleMethod("another value");\n};\n\n// ExampleClass.test.js\nimport {fooBar} from \'./OtherModule\';\nimport {ExampleClass} from \'./ExampleClass\';\njest.mock(\'./ExampleClass\');\n\nit(\'try to create a mock of ExampleClass\', () => {\n ExampleClass.mockClear();\n\n fooBar();\n\n // to verify values for of instance method "exampleMethod" of ExampleClass instance\n expect(ExampleClass.mock.instances[0].exampleMethod.calls.length).toBe(1);\n expect(ExampleClass.mock.instances[0].exampleMethod.calls[0][0]).toBe("another value");\n\n // How to verify values for **constructor** of ExampleClass ?????\n // expect(ExampleClass.mock.instances[0].constructor.calls.length).toBe(1);\n // expect(ExampleClass.mock.instances[0].constructor.calls[0][0]).toBe("another value");\n});\nRun Code Online (Sandbox Code Playgroud)\n\n我不知道该怎么做(以及在注释代码中提到的)是如何监视/访问构造函数的值(而不仅仅是实例方法)。
\n\n任何帮助将不胜感激!\xe2\x9d\xa4
\nExampleClass 是构造函数,由于整个模块是自动模拟的,因此它已经设置为模拟函数:
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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12165 次 |
| 最近记录: |