gpt4 book ai didi

在 AngularJS 和 Testacular 中测试广播

转载 作者:行者123 更新时间:2023-11-28 19:51:14 27 4
gpt4 key购买 nike

我正在使用 angular-http-auth拦截 401 响应的模块。如果有可以用 $on() 接收的 401 响应,此模块将广播 event:auth-loginRequired。但是我该如何测试呢?

beforeEach(inject(function($injector, $rootScope) {
$httpBackend = $injector.get('$httpBackend');
myApi = $injector.get('myApi');
scope = $rootScope.$new();
spyOn($scope, '$on').andCallThrough();
}));
describe('API Client Test', function() {
it('should return 401', function() {
$httpBackend.when('GET', myApi.config.apiRoot + '/user').respond(401, '');
myApi.get(function(error, success) {
// this never gets triggered as 401 are intercepted
});
scope.$on('event:auth-loginRequired', function() {
// This works!
console.log('fired');
});

// This doesn't work
expect($scope.$on).toHaveBeenCalledWith('event:auth-loginRequired', jasmine.any(Function));

$httpBackend.flush();
});
});

最佳答案

根据您的评论,我认为您不需要任何 expect($scope.$on).toHaveBeenCalledWith(...);,因为它确保某些东西真正监听了事件。

为了断言事件已触发,您必须准备好所有必要的东西,然后执行导致事件广播的操作。我想可以通过以下方式概述规范:

it('should fire "event:auth-loginRequired" event in case of 401', function() {
var flag = false;
var listener = jasmine.createSpy('listener');
scope.$on('event:auth-loginRequired', listener);
$httpBackend.when('GET', myApi.config.apiRoot + '/user').respond(401, '');

runs(function() {
myApi.get(function(error, success) {
// this never gets triggered as 401 are intercepted
});
setTimeout(function() {
flag = true;
}, 1000);
});

waitsFor(function() {
return flag;
}, 'should be completed', 1200);

runs(function() {
expect(listener).toHaveBeenCalled();
});
});

关于在 AngularJS 和 Testacular 中测试广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15410074/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com