bre*_*ter 2 javascript mocking ecmascript-6 jestjs
我有一个定义 2 个类的脚本,其中 1 个类从另一个类的构造函数中实例化。我如何模拟嵌套构造函数,以便我可以测试父构造函数?
export default class Foo {
// i want to test this constructor...
constructor() {
new Bar
}
}
export class Bar {
// but mock this constructor
constructor() {}
}
Run Code Online (Sandbox Code Playgroud)
另外,我试图监视 Bar 构造函数,以断言它已被调用
我尝试了几种不同的方法,但未能得到我想要的结果。我是笑话嘲笑库的新手
需要对模块导出语句做一点修改。然后,我们可以使用jest.spyOn(object, methodName)方法来模拟Bar类的实现。编译后看一下代码。我们在模块导出对象中创建模拟Bar并在类中使用它Foo。它与被嘲笑的引用具有相同的引用。
推荐方式:
\njest.mockorjest.doMock方法来模拟类。例如
\nindex.ts:
export default class Foo {\n constructor() {\n new exports.Bar();\n }\n}\n\nclass Bar {\n constructor() {\n console.log(\'real Bar constructor implmentation\');\n }\n}\n\nexports.Bar = Bar;\nRun Code Online (Sandbox Code Playgroud)\nindex.test.ts:
import * as mod from \'./\';\n\nconsole.log(mod);\n\ndescribe(\'64549093\', () => {\n it(\'should pass\', () => {\n const BarConstructorMock = jest.spyOn(mod as any, \'Bar\').mockImplementationOnce(() => {\n console.log(\'fake Bar constructor implmentation\');\n });\n new mod.default();\n expect(BarConstructorMock).toBeCalled();\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n单元测试结果:
\n PASS src/stackoverflow/64549093/index.test.ts (9.905s)\n 64549093\n \xe2\x9c\x93 should pass (5ms)\n\n console.log src/stackoverflow/64549093/index.test.ts:3\n { default: [Function: Foo], Bar: [Function: Bar] }\n\n console.log src/stackoverflow/64549093/index.test.ts:8\n fake Bar constructor implmentation\n\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 11.751s, estimated 12s\nRun Code Online (Sandbox Code Playgroud)\njestjs关于,的配置TypeScript,参见示例:\n https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/64549093
| 归档时间: |
|
| 查看次数: |
11545 次 |
| 最近记录: |