从窗口作用域函数调用的测试方法
Jasmine: testing method called from window scope function
我使用Jasmine来测试我的一些代码。它看起来有点像这样
# main logic
function Analytics() {
this.construct = function() {
}
this.foo = function() {
}
this.bar = function() {
}
}
# "main" routine, called by jQuery on ready, or direct by Jasmine
function analytics() {
new Analytics().construct();
}
# calls main routine
$(document).ready(function () {
analytics();
});
在浏览器中运行时,它工作得很好。然而,当我想用Jasmine测试我的代码时(测试在调用analytics()时是否调用了构造函数),它会失败。
Expected spy construct to have been called. (1)
说明如下:
it('should call the constructor when the document is ready', function({
var _analytics = new Analytics();
spyOn(_analytics, 'construct')
analytics(); # note this is the "main" routine
expect(_analytics.construct).toHaveBeenCalled();
})
我的测试用例似乎是不正确的,但我真的不知道如何。有人能解释一下这种行为吗?
正如我所看到的,从代码中"analytics"函数创建了analytics的新实例。
所以test可能是这样的:
it('should call the constructor when the document is ready', function({
var _analytics = new Analytics(); // --> create new instance of Analytics
spyOn(_analytics, 'construct') // --> spy on construct func
analytics(); // --> This, creates new instance
// of analytics which you don't spy on.
expect(_analytics.construct).toHaveBeenCalled();
});
尝试通过prototype:
spyOn(Analytics.prototype, 'construct'); // will spy all instances.
和test将看起来像这样:
it('should call the constructor when the document is ready', function({
spyOn(Analytics.prototype, 'construct');
analytics();
expect(Analytics.prototype.construct).toHaveBeenCalled();
});
注意你不能访问在分析函数中创建的实例。
创建后将无法使用。
我不知道任务的上下文。但也许你应该使用默认构造函数。
function Analytics(options) {
// this is constructor
this.prop1 = options.prop1;
this.prop2 = options.prop2;
this.foo = function() {
}
this.bar = function() {
}
}
var analyticsModule = new Analytics(options);
相关文章:
- 从全局函数调用Ember控制器上的方法
- 对中的函数调用进行排序是回调的唯一方法
- 函数调用方法有什么用
- Jasmine测试工厂函数调用本地函数和另一个函数-获取错误:应该是间谍,但得到了function
- 成功函数未在 ajax GET 方法中调用
- “未捕获(在承诺中)”在获取“then”方法中调用拒绝函数时
- Typescript从类的构造函数调用方法
- 如何在jquery的drop方法中调用函数
- Sinon-带有回调的存根函数-导致测试方法超时
- 如何在测试的函数中对外部模块进行调用
- 测试React函数是用Jest调用的
- 在方法中调用全局函数
- JQuery .ajax() 函数调用不起作用,但成功方法运行
- 从函数调用全局对象的方法
- 如何从Javascript函数调用控制器方法
- 如何隔离测试纯函数调用树
- Objective-C 方法/函数调用.(来自JavaScript示例)
- 如何测试函数是否调用了特定的方法/函数
- 处理setTimeout(javascript)中的对象方法函数调用
- 从窗口作用域函数调用的测试方法