Sinon: mocking , stubbing a typescript interface

Created on 2 Sep 2018  路  1Comment  路  Source: sinonjs/sinon

It would be very great if sinon could mock or stub a typescript interface. When coding in DI way, dependencies are injected by some IoC container. I think testing would be even nice with interface mocking ability. Something like:

interface IDependency{
...
}

const stub = sinon.stubOf<IDependency>();
const mock = sinon.mockOf<IDependency>();

Is it possible?

Most helpful comment

No - not at runtime. For one thing, Sinon is javascript library, targetting Javascript (strictly speaking, ES5.1, with some minor handling of ES6 classes). It works with TypeScript as TypeScript compiles down to Javascript. Once Typescript has been compiled to Javascript the type information is lost (AFAIK!). That means run-time reflection logic on interfaces (which is gone after compilation) is not possible.

That doesn't mean what you want is not possible, just that Sinon can't do it. You would need some logic at compile-time (parse-time) that would build ASTs and such from the interfaces and create it for you. Look at Esprima and such for tooling. Once whatever tool you create has made some kind of stub interface you could then use that in your code (probably using some kind of Sinon add-on).

>All comments

No - not at runtime. For one thing, Sinon is javascript library, targetting Javascript (strictly speaking, ES5.1, with some minor handling of ES6 classes). It works with TypeScript as TypeScript compiles down to Javascript. Once Typescript has been compiled to Javascript the type information is lost (AFAIK!). That means run-time reflection logic on interfaces (which is gone after compilation) is not possible.

That doesn't mean what you want is not possible, just that Sinon can't do it. You would need some logic at compile-time (parse-time) that would build ASTs and such from the interfaces and create it for you. Look at Esprima and such for tooling. Once whatever tool you create has made some kind of stub interface you could then use that in your code (probably using some kind of Sinon add-on).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

brettz9 picture brettz9  路  3Comments

zimtsui picture zimtsui  路  3Comments

stephanwlee picture stephanwlee  路  3Comments

NathanHazout picture NathanHazout  路  3Comments

byohay picture byohay  路  3Comments