Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.

How to I use stub with TypeScript #260

Open
ujbrody opened this issue Jun 8, 2022 · 0 comments
Open

How to I use stub with TypeScript #260

ujbrody opened this issue Jun 8, 2022 · 0 comments

Comments

@ujbrody
Copy link

ujbrody commented Jun 8, 2022

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?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant