使用 Sinon.JS 和 Rewire 时是否可以设置 `this` 的值?
Is it possible to set the value of `this` when using Sinon.JS and Rewire?
背景
如果我有以下模块:
this_module: {
foo: {};
set_this_foo: function () {
this.foo.boo = 'something';
return this.foo;
}
}
并使用 Rewire to import the private function and then unit test this function using Sinon.js:
var set_this_foo = app.__get__('this_module.set_this_foo');
var spy = sinon.spy(set_this_foo);
spy();
expect(spy).to.have.returned({boo: 'something'});
我收到错误消息:
TypeError: Cannot set property 'boo' of undefined
因为this
最终得到了全局对象的值。我可以通过在 运行 测试之前定义一个名为 foo
的全局变量来解决这个问题,但我不想污染全局命名空间。
问题
是否有一种(优雅的)方法来定义 this
相对于 spy()
的值?
我会做一些不同的事情:
var myModule = app.__get__('this_module');
var spy = sinon.spy(myModule, 'set_this_foo');
myModule.set_this_foo();
expect(spy).to.have.returned({ boo : 'something' });
由于您还可以使用原始方法名称(除了 spy
之外)来引用间谍程序,因此调用它将确保在正确的上下文中调用它。
背景
如果我有以下模块:
this_module: {
foo: {};
set_this_foo: function () {
this.foo.boo = 'something';
return this.foo;
}
}
并使用 Rewire to import the private function and then unit test this function using Sinon.js:
var set_this_foo = app.__get__('this_module.set_this_foo');
var spy = sinon.spy(set_this_foo);
spy();
expect(spy).to.have.returned({boo: 'something'});
我收到错误消息:
TypeError: Cannot set property 'boo' of undefined
因为this
最终得到了全局对象的值。我可以通过在 运行 测试之前定义一个名为 foo
的全局变量来解决这个问题,但我不想污染全局命名空间。
问题
是否有一种(优雅的)方法来定义 this
相对于 spy()
的值?
我会做一些不同的事情:
var myModule = app.__get__('this_module');
var spy = sinon.spy(myModule, 'set_this_foo');
myModule.set_this_foo();
expect(spy).to.have.returned({ boo : 'something' });
由于您还可以使用原始方法名称(除了 spy
之外)来引用间谍程序,因此调用它将确保在正确的上下文中调用它。