如何使用 jest 模拟从方法内部启动的构造函数

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 构造函数,以断言它已被调用

我尝试了几种不同的方法,但未能得到我想要的结果。我是笑话嘲笑库的新手

sli*_*wp2 5

需要对模块导出语句做一点修改。然后,我们可以使用jest.spyOn(object, methodName)方法来模拟Bar类的实现。编译后看一下代码。我们在模块导出对象中创建模拟Bar并在类中使用它Foo。它与被嘲笑的引用具有相同的引用。

\n

推荐方式:

\n
    \n
  1. 依赖注入
  2. \n
  3. 每个文件仅包含一个类。这样我们就可以在不修改模块导出语句的情况下使用jest.mockorjest.doMock方法来模拟类。
  4. \n
\n

例如

\n

index.ts:

\n
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;\n
Run Code Online (Sandbox Code Playgroud)\n

index.test.ts:

\n
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});\n
Run 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\n
Run Code Online (Sandbox Code Playgroud)\n

jestjs关于,的配置TypeScript,参见示例:\n https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/64549093

\n