我们正在使用角度1.2.x(我们必须使用IE8)。我们正在测试Karma和Jasmine。我想测试模块的行为,以防服务器响应错误。根据角度文档,我应该简单地准备这样的$ httpBackend mock(完全按照我的预期):
authRequestHandler = $httpBackend.when('GET', '/auth.py');
// Notice how you can change the response even after it was set
authRequestHandler.respond(401, '');
这就是我在测试中所做的事情:
beforeEach(inject(function($injector) {
keepSessionAliveService = $injector.get('keepSessionAliveService');
$httpBackend = $injector.get('$httpBackend');
$interval = $injector.get('$interval');
}));
(...)
describe('rejected keep alive request', function() {
beforeEach(function() {
spyOn(authStorageMock, 'get');
spyOn(authStorageMock, 'set');
$httpBackend.when('POST', keepAliveUrl).respond(500, '');
keepSessionAliveService.start('sessionId');
$interval.flush(90*60*1001);
$httpBackend.flush();
});
it('should not add the session id to the storage', function() {
expect(authStorageMock.set).not.toHaveBeenCalled();
});
});
但是测试失败了,因为正在调用mock函数,我可以在代码覆盖中看到它永远不会运行到错误函数中,而是作为第二个参数传递给§promise.then。
显然我在这里做错了。它可能与我们使用的旧版角度版本有关吗?
任何帮助将不胜感激!
答案 0 :(得分:0)
这样的事情:
it("should receive an Ajax error", function() {
spyOn($, "ajax").andCallFake(function(e) {
e.error({});
});
var callbacks = {
displayErrorMessage : jasmine.createSpy()
};
sendRequest(callbacks, configuration);
expect(callbacks.displayErrorMessage).toHaveBeenCalled();