vendredi 27 mai 2016

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 this:

const client = restify.createJsonClient({
    url: 'http://www.example.com'
});
export let get = promisify(client.get, {thisArg: client, multiArgs: true});

export default function* () {
    yield get('/some/path');
}

And then in my test file I have something like this:

import * as m from mymodule;
it('should fail', function(done) {
    let stub = sinon.stub(m, 'get').rejects('i failed');
    client.get('/endpoint/that/leads/to/mymodule/call', function(err, req, res, data) {
        stub.called.should.be.eql(true); // assertion fails!!
        done();
    }
});

I've also tried stubbing the original client.get call, and that doesn't work either. The only thing I've gotten to work is promisifying on the fly with each call, and stubbing the original client.get, which seems pretty lame. E.g.:

export const client = restify.createJsonClient({
    url: 'http://www.example.com'
});
function get() {
    return promisify(client.get, {thisArg: client, multiArgs: true});
}

export default function* () {
    yield get('/some/path');
}

And test code doing this:

import {module_client} from mymodule;
it('should fail', function(done) {
    let stub = sinon.stub(module_client, 'get').yields('i failed');
    client.get('/endpoint/that/leads/to/mymodule/call', function(err, req, res, data) {
        stub.called.should.be.eql(true); // assertion succeeds
        done();
    }
});

And so the question, if it's not completely obvious, is why does my original code not work? And is there a way to make the stub work without promisifying the original restify each time (e.g. how do other people get this sort of thing working)?

Aucun commentaire:

Enregistrer un commentaire