I'm trying to stub a class instance using sinon.createStubInstance
but I'm getting an error stating that a private member variable is missing. Of course I can't explicitly set it either because it's a private member.
Example classes:
class Foo {
private readonly bar: string;
constructor(bar: string) {
this.bar = bar;
}
}
class Parent {
foos: Foo[];
constructor(foos: Foo[]) {
this.foos = foos;
}
}
And in the test I'm writing a beforeEach
block:
beforeEach(function () {
const stubFoo = sinon.createStubInstance(Foo);
const stubParent = sinon.createStubInstance(Parent);
stubParent.foos = [stubFoo]; // Tslint error here
});
The Tslint error is:
Property 'bar' is missing in type 'SinonStubbedInstance' but required in type 'Foo'
For the record I'm using Typescript v3.0.3 and Sinon v7.4.1.
I personally like this solution found by a Github user (paulius-valiunas):
if you just want to use this in a couple places, a simpler and more readable solution would be to use the type alias
StubbedClass<T> = SinonStubbedInstance<T> & T
directly. For example:export type StubbedClass<T> = SinonStubbedInstance<T> & T; const myStub = sinon.createStubInstance(MyClass) as StubbedClass<MyClass>;
or just:
const myStub = sinon.createStubInstance(MyClass) as SinonStubbedInstance<MyClass> & MyClass;
way cleaner and simpler than other suggestions!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With