Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ts-sinon: Property 'returns' does not exist on type

I am writing an application using Typescript, and want to create unit tests with ts-sinon.

In their README, they state that you can stub methods like this:

import * as sinon from 'ts-sinon'

class Test {
    method() { return 'original' }
}

const test = new Test();
const testStub = sinon.stubObject<Test>(test);

testStub.method.returns('stubbed');

expect(testStub.method()).to.equal('stubbed');

But this code gives me this error:

Property 'returns' does not exist on type '() => string'.

What am I doing wrong?

like image 812
Titulum Avatar asked Jun 20 '19 20:06

Titulum


1 Answers

I was having a similar issue, and this post was a false positive for me. I thought it worth pointing out that when I put the code in the following test, it works as expected.

/* eslint-disable @typescript-eslint/explicit-function-return-type */
import * as chai from 'chai'
import * as sinon from 'ts-sinon'
const expect = chai.expect

class Test {
  public method() : string {return `original`}
}

const test = new Test()

describe.only(`ts-sinon stubObject()<Test> should`, () => {
  it(`return the expected value`, () => {
    const testStub = sinon.stubObject<Test>(test)
    testStub.method.returns(`stubbed`)
    expect(testStub.method()).to.equal(`stubbed`)
  })
})

The problem I was having involved not setting the correct type for my stub. The following example adds a beforeEach and scopes the stub at a higher level. It was setting the incorrect stub type that caused my "Property returns does not exist" error.

/* eslint-disable @typescript-eslint/explicit-function-return-type */
import * as chai from 'chai'
import * as sinon from 'ts-sinon'
const expect = chai.expect

class Test {
  public method() : string {return `original`}
}

describe.only(`ts-sinon stubObject()<Test> should`, () => {
  let testStub: sinon.StubbedInstance<Test> // <- Type the stub correctly
  beforeEach(() => {
    const test = new Test()
    testStub = sinon.stubObject<Test>(test)
    testStub.method.returns(`stubbed`)
  })
  it(`return the expected value`, () => {
    expect(testStub.method()).to.equal(`stubbed`)
  })
})
like image 89
Tod Avatar answered Sep 20 '22 17:09

Tod