在jasmine测试代码中未调用回调函数
Callback function not get called in jasmine test code
我正在使用jasmine 2.0进行测试,我正在监视jquery ajax并返回一个promise。在done()函数中,方法displayContent()不会被调用,但它上面的控制台消息会显示出来。我哪里错了?
test.js
it(..., function() {
var data = {"name" : "John Doe"};
spyOn($, 'ajax').and.callFake(function (req) {
var d = $.Deferred();
d.resolve(data);
return d.promise();
});
app.doSomething();
expect(app.doSomething).toHaveBeenCalled();
})
app.js
app.getData = function() {
var jsonData = app.loadEmpData(); //gets replaced by spy and returns resolve(data);
jsonData.done(function(data) {
console.log("shows up in the console");
app.displayContent(data); // doesn't get called
});
jsonData.fail(function(){
console.log("error loading data");
});
}
app.loadEmpData = function() {
return $.getJSON("/employee.json");
}
app.displayContent = function() {
console.log("some content");
}
app.doSomething = function() {
app.getData();
}
我脑海中弹出两个可能的选项:
1) 在某些情况下,您应该在测试代码中调用$scope.apply(),以确保promise的then函数得到执行。
2) 您可以使用done()函数,如下所示:
it('', function(done){
$promise.then(function(){
expect(...);
done();
})
});
监视displayContent()
并检查是否调用了它。我修改了你的测试,调用了displayContent()
。替换为此代码并进行检查。
it("some test", function() {
var data = {"name" : "John Doe"};
spyOn($, 'ajax').and.callFake(function (req) {
var d = $.Deferred();
d.resolve(data);
return d.promise();
});
spyOn(app, 'displayContent').and.callThrough();
app.getData();
expect(app.displayContent).toHaveBeenCalled();
});
在Jasmine 2.0中,and.callThrough();
将委托给displayContent()
的实际实现。
相关文章:
- 为什么(如何)'这'从函数内部调用回调时发生更改
- 在初始函数完成之前调用回调函数
- Node.js exec调用从不调用回调
- 如何从参数数组中调用回调
- 如何在调用回调之前禁用按钮
- 加载文件,然后调用回调函数
- async.retry-已调用回调
- 节点.js“已调用回调”.但是没有任何其他回调
- JavaScript - 返回承诺和/或调用回调
- 解析查询.首次成功/错误 间歇性不调用回调
- 如何使用另一个 JavaScript 文件中定义的类名调用回调函数
- ReactJs:this.setState的情况下不调用回调函数
- $.post到PHP文件-在包含循环完成之前不会调用回调
- 异步加载ASP.NET绑定的Javascript,然后调用回调
- setTimeout()在其设置时间之前连续调用回调函数
- 在其他回调js中调用回调
- Ajax 调用重新加载页面,而不是调用回调函数
- Angularjs $http.get 不调用回调
- 未调用回调函数
- jQuery JSONP 不调用回调