简体   繁体   中英

node, unit-testing and mocking with sinon

So I am using a test suite of Chai, rewire, sinon, and sinon-chai to test some node javascript. This is my first time trying to set this up so I could use some pointers. The function I am trying to test looks like so :

UserRoles.get = function(ccUrl, namespace, environment, ccToken, authPath) {
    var crowdControl = new CrowdControl(ccUrl, namespace, environment, ccToken, authPath);
    return q.Promise(function(resolve, reject) {
        crowdControl.get().then(resolve).fail(reject).done();
    });
};

Inside a document that exports as UserRoles. So I have the initial set up working fine, where I am having troubles is mocking to test this function. I'm trying to mock the new CrowdContol part so my attempt to do that looks like so : https://jsfiddle.net/d5dczyuk/ .

so I'm trying out the

testHelpers.sinon.stub(CrowdControl, "UserRoles");

to intercept and stub

var CrowdControl = require('./crowdcontrol');

then just running

userRoles.get;

console.log(CrowdControl);

And it seems the stub is not being called ( it logs it's a stub but not that it has been called). I will also need to stub the crowdControl.get() hopefully too, however I was trying to get this simple part working first. Not sure what I need to be doing differently to get this to work here. This is my first time unit testing in node, I've done a bunch in angular where I could just "mock" the CrowdControl, but I'm not sure how it works in node.

Just to clarify I am just checking if CrowControl will be called with those vars passing in, should I just stub it? but I also want to mock the crowdControl so I can force what the get returns.

Edit: here is my second attempt : https://jsfiddle.net/5m5jwk5q/

I like to use proxyquire for this kind of testing. With proxyquire you can stub out require'd dependencies from the modules you're trying to test. So in your case you could do:

var crowdControlSpy = sinon.spy();

// Makes sure that when ./user-roles tries to require ./crowdcontrol
// our controlled spy is passed, instead of the actual module.
var UserRoles = proxyquire('./user-roles', {
    './crowdcontrol': crowdControlSpy
});

UserRoles.get(...);
expect(crowdControlSpy).to.have.been.called;

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