Reputation: 5644
How to stub this.desires.eat
?
const sinon = require('sinon');
const expect = require('expect.js');
class Cat {
constructor() {
this.desires = {
eat: () => 'for a mouse'
}
}
breakfast() {
return 'go ' + this.desires.eat();
}
}
const twinky = new Cat();
sinon.stub(twinky, 'desires.eat', () => {
return 'fishing';
});
describe('test cat', () => {
it('cat is going to have breakfast', (done) => {
const solution = twinky.breakfast();
expect(solution.includes('fishing')).to.be(true);
done();
});
});
Now I have the following error:
/media/trex/safe1/Development/app/node_modules/sinon/lib/sinon/util/core.js:115
throw error;
^
TypeError: Attempted to wrap undefined property desires.eat as function
at Object.wrapMethod (/media/trex/safe1/Development/app/node_modules/sinon/lib/sinon/util/core.js:106:29)
at Object.stub (/media/trex/safe1/Development/app/node_modules/sinon/lib/sinon/stub.js:67:26)
at Object.<anonymous> (/media/trex/safe1/Development/app/server/lib/test.js:19:7)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
Upvotes: 1
Views: 108
Reputation: 1075209
From the docs it looks like:
sinon.stub(twinky.desires, 'eat', () => {
return 'fishing';
});
E.g., since the method is on twinky.desires
, pass that in rather than twinky
and then just pass eat
as the method name. Apparently sinon doesn't parse dotted notation strings and dive down into the object (which is perfectly reasonable for it not to do).
Upvotes: 1