简体   繁体   English

完全或部分在 TypeScript 中模拟类和接口

[英]Mock classes and interfaces, fully or partially in TypeScript

What is the best way to mock classes and interfaces, fully or partially in TypeScript?在 TypeScript 中完全或部分模拟类和接口的最佳方法是什么?

Jest is a popular test stack with mocking support, however according to this mocking single methods, classes and interfaces isn't supported in a fluent manner. Jest 是一种流行的支持模拟的测试堆栈,但是根据这种模拟单一方法,类和接口不以流畅的方式支持。

There are numerous mocking libraries specifically for TypeScript.有许多专门用于 TypeScript 的模拟库。 Substitute.js is an excellent one. Substitute.js是一个很好的例子。 At the time of writing it addresses shortcomings in others, including:在撰写本文时,它解决了其他方面的缺点,包括:

  • Fluent API.流畅的API。 ts-mockito has a fluent API, however it is unable to mock interfaces. ts-mockito 有一个流畅的 API,但是它不能模拟接口。 This is a show-stopper.这是一个表演障碍。
  • Ability to create partial mocks.能够创建部分模拟。

It can also be fairly simply achieved with jest, as follows:使用 jest 也可以相当简单地实现,如下所示:

ClientDefaultImpl.prototype.authorize = jest.fn().mockImplementationOnce(
            () => Promise.resolve('xxx'));

Edit:编辑:

ts-mockito supports mocking of classes (and interfaces?) now. ts-mockito 现在支持模拟类(和接口?)。

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

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