How To Spy A Function With Sinon.js That Is In The Same Js File As The Function Under Test
I have a problem with Sinon.js while trying to spy a function that is in the same javascript file as the function that I want to test. Furthermore I assert that the spied function
Solution 1:
Unfortunately the test fails
That is because one.some_method() in mock_test.js invokes another_method inside the closure one.some_method() is holding over the content of one.js and not one.another_method in mock_test.js.
Illustration by example
Lets re-write one.js to:
vara='I am exported';
varb='I am not exported';
function foo() {
console.log(a);
console.log(this.b)
}
module.exports.a=a;
module.exports.foo=foo;
and mock_test.js to:
var one = require('./one');
console.log(one); // { a: 'I am exported', foo: [Function: foo] }
one.a = 'Charles';
one.b = 'Diana';
console.log(one); // { a: 'Charles', foo: [Function: foo], b: 'Diana' }Now if we invoke one.foo() it will result in:
I am exported
Diana
The I am exported is logged to the console because console.log(a) inside foo points to var a inside the closure foo is holding over the contents of one.js.
The Diana is logged to the console because console.log(this.b) inside foo points to one.b in mock_test.js.
So what do you need to do to make it work?
You need to change:
var some_method = function(){
console.log('one: some method')
another_method()
}
to:
var some_method = function(){
console.log('one: some method')
this.another_method()
}
Post a Comment for "How To Spy A Function With Sinon.js That Is In The Same Js File As The Function Under Test"