javascript - How to spy a function with Sinon.js that is in the same js file as the function under test -
i have problem sinon.js while trying spy function in same javascript file function want test. furthermore assert spied function called once. unfortunately test fails. interesting thing is, if spied function in javascript file function under test works !
here code:
mock_test.js:
var sinon = require('sinon') var 1 = require('./one.js') var 2 = require('./two.js') describe('spy ', function () { it('spy method', sinon.test(function (done) { var another_method_spy = sinon.spy(one, 'another_method') one.some_method() sinon.assert.calledonce(another_method_spy) done() })) it('spy second method', sinon.test(function (done) { var second_method = sinon.spy(two, 'second') one.call_second() sinon.assert.calledonce(second_method) done() })) })
one.js:
var 2 = require('./two.js') var some_method = function(){ console.log('one: method') another_method() } var another_method = function(){ console.log('one: method') } var call_second = function(){ console.log('one: call second') two.second() } module.exports.some_method = some_method module.exports.another_method = another_method module.exports.call_second = call_second
two.js:
var second = function(){ console.log('two: second') } module.exports.second = second
i couldn't find helpful in internet , tried different things. please help, missing here ?
cheers noah
unfortunately test fails
that because one.some_method()
in mock_test.js invokes another_method
inside closure one.some_method()
holding on content of one.js , not one.another_method
in mock_test.js.
illustration example
lets re-write one.js to:
var = 'i exported'; var b = 'i 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 1 = require('./one'); console.log(one); // { a: 'i exported', foo: [function: foo] } one.a = 'charles'; one.b = 'diana'; console.log(one); // { a: 'charles', foo: [function: foo], b: 'diana' }
now if invoke one.foo()
result in:
i exported diana
the i exported
logged console because console.log(a)
inside foo
points var a
inside closure foo
holding on contents of one.js.
the diana
logged console because console.log(this.b)
inside foo
points one.b
in mock_test.js.
so need make work?
you need change:
var some_method = function(){ console.log('one: method') another_method() }
to:
var some_method = function(){ console.log('one: method') this.another_method() }
Comments
Post a Comment