简体   繁体   中英

Using Sinon with Typescript and interfaces

Say I have a class like this:

export class User implements Employee {
    lanId: string;
    firstName: string;
    lastName: string;
}

and an interface like this:

export interface Employee {
     firstName: string;
     lastName: string;
}

I then want to use Sinon to make a fake user:

user = sinon.createStubInstance(User);

This gives an error like this:

Cannot convert type 'SinonStub' to type 'Employee'. Type 'Employee' has non-optional property 'firstName' which is not present on type 'SinonStub'.

It seems like Typescript and Sinon are unhappy together.

Is there a way to create a SinonStub of a class that implements a Typescript interface?

Is the user object marked as being of type 'Employee'? If so, this error makes sense.

sinon.createStubInstance(User) will return an object meeting the SinonStub interface which as the compiler warns is not compliant with the Employee interface.

If you don't annotate the type of user typescript moves forward assuming it is a SinonStub and you won't run into the issue. If you haven't actually annotated it, it's possible the variable picked up the annotation implicitly through usage elsewhere.

If that sounds off, is there something you're trying to accomplish that isn't in the question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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