简体   繁体   English

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

[英]how to mock a constructor being initiated from inside a method with jest

i have a script that defines 2 classes, and 1 gets instantiated from within the constructor of the other.我有一个定义 2 个类的脚本,其中 1 个从另一个类的构造函数中实例化。 how can i mock the nested constructor, so i can test the parent constructor?我如何模拟嵌套构造函数,以便测试父构造函数?

export default class Foo {
  // i want to test this constructor...
  constructor() {
    new Bar
  }
}

export class Bar {
  // but mock this constructor
  constructor() {}
}

additionally, i am trying to spy on the Bar constructor, to assert that it has been called此外,我试图监视 Bar 构造函数,以断言它已被调用

i have tried several different approaches, but haven't been able to get the results i am looking for.我尝试了几种不同的方法,但无法获得我想要的结果。 i am new to the jest mocking library我是开玩笑 mocking 图书馆的新手

Need to make a little modification to the module export statement.需要对模块导出语句做一点修改。 Then, we can use jest.spyOn(object, methodName) method to mock implementation for Bar class. Take a look at the code after compiling.然后,我们可以使用jest.spyOn(object, methodName)方法来模拟Bar class 的实现。看看编译后的代码 We create the mocked Bar in the module export object and we use it in the Foo class. It has the same reference as the mocked one.我们在模块 export object 中创建模拟的Bar并在Foo class 中使用它。它与模拟的具有相同的引用。

Recommend way:推荐方式:

  1. Dependency Injection依赖注入
  2. Each file contains ONLY ONE class. So that we can use jest.mock or jest.doMock method to mock the class without modifying the module export statement.每个文件仅包含一个 class。这样我们就可以使用jest.mockjest.doMock方法来模拟 class 而无需修改模块导出语句。

Eg例如

index.ts : index.ts

export default class Foo {
  constructor() {
    new exports.Bar();
  }
}

class Bar {
  constructor() {
    console.log('real Bar constructor implmentation');
  }
}

exports.Bar = Bar;

index.test.ts : index.test.ts

import * as mod from './';

console.log(mod);

describe('64549093', () => {
  it('should pass', () => {
    const BarConstructorMock = jest.spyOn(mod as any, 'Bar').mockImplementationOnce(() => {
      console.log('fake Bar constructor implmentation');
    });
    new mod.default();
    expect(BarConstructorMock).toBeCalled();
  });
});

unit test result:单元测试结果:

 PASS  src/stackoverflow/64549093/index.test.ts (9.905s)
  64549093
    ✓ should pass (5ms)

  console.log src/stackoverflow/64549093/index.test.ts:3
    { default: [Function: Foo], Bar: [Function: Bar] }

  console.log src/stackoverflow/64549093/index.test.ts:8
    fake Bar constructor implmentation

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.751s, estimated 12s

About the configuration of jestjs , TypeScript , see example: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/64549093关于jestjs , TypeScript的配置,见示例: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/64549093

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM