【发布时间】:2014-05-01 12:41:32
【问题描述】:
我有一个名为 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 秒)。
有人可以帮我提供我的代码的工作示例和一些解释吗?
【问题讨论】:
-
处理事件通常在一个摘要循环中完成。尝试将 scope.$apply() 添加到您的测试中,而不是使用 Jasmine 的异步测试模式
-
这不起作用。我添加了 scope.$apply();刚刚调用 requestNotificationChannel.deleteMessage(1, 4) 但我收到同样的错误...
-
async tests take longer to run than
Jestexpects 时出现同样的错误 - 在调试和检查变量时很常见。 -
尝试使用较小的超时时间。使用 timeout = 5000 时出现此错误。我将其替换为 2000,它对我有用!
-
把这个留在这里是为了帮助像我一样的人。在 docker 容器内运行测试时出现此错误。测试有时会毫无问题地通过,但有时会失败。我认为这是某种比赛条件,但不知道为什么。我意识到我有一个
afterEach步骤正在清除数据库(使用deleteMany方法)。在beforeAll方法中添加jest.setTimeout(30000);似乎已经为我解决了这个问题 - 我猜因为数据库删除是一个网络调用(在条件内),它有时需要超过 3 秒并抛出。
标签: javascript angularjs unit-testing asynchronous jasmine