如何在Typescript类中使用Sinon JS模拟

时间:2019-06-26 07:30:02

标签: typescript unit-testing sinon

我正在尝试使用SinonJS进行单元测试的模拟,但是从概念上讲,我碰壁了,认为我缺少一些东西。

我使用注入构造函数中服务类的所有依赖项。因此,想像这样的服务:

class MyService {

  protected otherService: OtherService;

  constructor(os: OtherService) {
    this.otherService = ds;
  }

  public someMethod() {
    this.otherService.doSomething();
  }

}

我现在正在按以下方式初始化测试:

describe('Launcher Renderer', () => {

    //dependencies (mocked)
    const os = sinon.mock(new OtherService());

    // the renderer class
    let underTest: MyService;

    before(() => {
        underTest = new MyService(os);
    });

    // actual tests,....
});

这当然不会编译,因为类型sinon.mock返回的类型是SinonMockStatic。在出现问题之前,出于某些原因,我确实想在此处使用模拟对象,而不是对方法进行存根/监视。

我想出的解决方案是将OtherServiceMyService的类型更改为OtherService | any。结果:

class MyService {

  protected otherService: OtherService | any;

  constructor(os: OtherService | any) {
    this.otherService = ds;
  }

  public someMethod() {
    this.otherService.doSomething();
  }

}

这有效,但对我来说似乎很难看。它完全破坏了类型安全性,而这实际上是Typescript的好处。我不喜欢的另一件事是,我必须修改原始代码,插入仅与测试有关的类型,并且测试不是透明的(例如,当我将Spring Boot与Mockito一起使用时)。 / p>

在这里,是否可以使用带有打字稿的sinon的良好模式?

0 个答案:

没有答案