我有一个名为 requestNotificationChannel
的 Angular 服务:
app.factory("requestNotificationChannel", function($rootScope) {
var _DELETE_MESSAGE_ = "_DELETE_MESSAGE_";
function deleteMessage(id, index) {
$rootScope.$broadcast(_DELETE_MESSAGE_, { id: id, index: index });
};
return {
deleteMessage: deleteMessage
};
});
我正在尝试使用 jasmine 对该服务进行单元测试:
"use strict";
describe("Request Notification Channel", function() {
var requestNotificationChannel, rootScope, scope;
beforeEach(function(_requestNotificationChannel_) {
module("messageAppModule");
inject(function($injector, _requestNotificationChannel_) {
rootScope = $injector.get("$rootScope");
scope = rootScope.$new();
requestNotificationChannel = _requestNotificationChannel_;
})
spyOn(rootScope, '$broadcast');
});
it("should broadcast delete message notification", function(done) {
requestNotificationChannel.deleteMessage(1, 4);
expect(rootScope.$broadcast).toHaveBeenCalledWith("_DELETE_MESSAGE_", { id: 1, index: 4 });
done();
});
});
我读到了 Jasmine 中的异步支持,但由于我对使用 javascript 进行单元测试相当陌生,因此无法使其工作。
我收到错误:
Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL
我的测试执行时间太长(大约 5 秒)。
有人可以帮我提供代码的工作示例并进行一些解释吗?
最佳答案
在 it
函数中包含参数(下面代码中的 done
)将导致 Jasmine 尝试异步调用。
//this block signature will trigger async behavior.
it("should work", function(done){
//...
});
//this block signature will run synchronously
it("should work", function(){
//...
});
done
参数的名称并不重要,重要的是它的存在。我因为太多的复制/面食而遇到了这个问题。
Jasmine Asynchronous Support文档指出,参数(上面名为 done
)是一个回调,可以调用它来让 Jasmine 知道异步函数何时完成。如果您从不调用它,Jasmine 将永远不会知道您的测试已完成,并且最终会超时。
关于javascript - jasmine:在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时内未调用异步回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22604644/