Sinon Stub With Es6-promisified Object
Ok my setup is as follows: Using node 6.2, es6-promisify, sinon, sinon-as-promised, and babel to transpile support for es6 import/export. My code under test looks something like th
Solution 1:
The problem ultimately has to do with how ES6 import/exports work, and specifically, how they make your code look better but prevent easy spying/stubbing.
Take this example module:
// my-module.js
function someFunction() {
console.log('original');
};
export let get = someFunction;
export default function() {
get();
};
A test case for that code could look like this:
import * as sinon from 'sinon';
import * as should from 'should';
import setup, * as myModule from './my-module';
it('should call get()', () => {
let stub = sinon.stub(myModule, 'get');
setup();
stub.called.should.eql(true);
});
You'll see that the original get()
gets called, and not the stub. This is because in the module, get
is a local (to the module) reference. Sinon is stubbing another reference to the same function, in the exported object.
To make this work, instead of using a local reference in the module, you need to use the one in the exported object:
export default function() {
exports.get();
};
Which, alas, makes for uglier code.
Post a Comment for "Sinon Stub With Es6-promisified Object"