Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using SinonJS in Typescript private properties are reported as missing

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.

like image 408
Mark Avatar asked Sep 25 '19 14:09

Mark


1 Answers

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!

like image 164
Guilherme Matuella Avatar answered Oct 03 '22 11:10

Guilherme Matuella