fancy-test icon indicating copy to clipboard operation
fancy-test copied to clipboard

How to I use stub with TypeScript

Open ujbrody opened this issue 3 years ago • 0 comments

I'm really having difficulty figuring out how to perform tests using the stub when using TypeScript, and I cannot find much information about it.

Here is a simple test I wrote to learn how to use the library:

import mongoose from 'mongoose';
import sinon from 'sinon';

...

test
        .stub(mongoose, 'connect', sinon.stub().returns('foo'))
        .it('use sinon', () => {
          expect(mongoose.connect('bar')).to.equal('foo');
          expect(mongoose.connect.called).to.be.true;
        });

This doesn't compile in TS since the connect function in Mongoose doesn't actually have a property called, and the TS compiler doesn't understand it's a stub.

I found out that the ctx value that is passed includes a collection of all stubs, so I tried to change the code to this:

test
        .stub(mongoose, 'connect', stub().returns('foo'))
        .it('use sinon', ctx => {
          expect(mongoose.connect('bar')).to.equal('foo');
          expect(ctx.stubs[0].called).to.be.true;
        });

This at least compiles, but the test fails with AssertionError: expected undefined to be true. In fact, none of the stub methods or properties exist on whatever is in that stubs array—just functions.

How can I get to the actual Sinon.stub to call on methods such as calledWith and the like?

ujbrody avatar Jun 08 '22 21:06 ujbrody