1

What is the best way to mock classes and interfaces, fully or partially in 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.

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185

1 Answers1

3

There are numerous mocking libraries specifically for TypeScript. Substitute.js is an excellent one. At the time of writing it addresses shortcomings in others, including:

  • Fluent API. ts-mockito has a fluent API, however it is unable to mock interfaces. This is a show-stopper.
  • Ability to create partial mocks.

It can also be fairly simply achieved with jest, as follows:

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

Edit:

ts-mockito supports mocking of classes (and interfaces?) now.

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185