简体   繁体   中英

How can I stub a constructor in node.js using sinon in a Cloud Functions for Firebase project?

I'm using GeoFire in a Cloud Functions for Firebase project I want to unit test.

In my original code GeoFire is used like this:

GeoFire = request('geofire');

...

var catGeoFire = new GeoFire(catGeofireRef);
return catGeoFire.set(storeId, [lat, lon]).then( () => {
    console.log("Added store " + storeId + " to GeoFire" );
        return Promise.resolve();
    });

I need to stub both the call to the GeoFire constructor and the GeoFire().set() method.

I tried:

const geofireStub = sinon.stub(GeoFire, 'set').resolves();

But I received the error:

TypeError: Cannot stub non-existent own property set

I also tried:

const setStub = sinon.stub().resolves();
const geofireStub = sinon.stub(GeoFire).returns({set: setStub});

And I receive the error:

TypeError: Cannot stub non-existent own property set

Both errors happen at the geofireStub line.

Reading the sinon documentation I understood that I can stub an object's methods. However in this case GeoFire isn't an object; it is a constructor function. So I don't really know how can I stub it without having an associated object.

Thanks!

You need something like that

 // target.js var GeoFire = require('geofire'); var catGeoFire = new GeoFire(catGeofireRef); return catGeoFire.set(storeId, [lat, lon]).then(() => { console.log("Added store " + storeId + " to GeoFire" ); return Promise.resolve(); }); // test.js var GeoFire = require('geofire'); var rewire = require('rewire') var target = rewire('./target') describe('target', () => { it('test case', () => { // arrange // configure instance var geoFireStub = sinon.createStubInstance(GeoFire) geoFireStub.set.resolves() // configure constuctor var GeoFireMock = sinon.stub().returns(geoFireStub) // 'GeoFire' is a mocked variable here var revert = rewire('GeoFire', GeoFireMock) // act (call tested module) target() // assert (should is just for example) should(GeoFireMock).calledWithNew(/* params*/) should(geoFireStub.set).calledWith(/* params*/) //cleanup (rewire and stubs, prefer to use sandbox) revert(); ... }) }) 

GeoFire is the constructor, but set is an instance method. You should stub GeoFire.prototype I believe.

sinon.stub(GeoFire.prototype, 'set').resolves();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM