gpt4 book ai didi

angularjs - 使用 andCallThrough() 在每个测试用例之后重置广播()

转载 作者:行者123 更新时间:2023-12-03 13:45:41 24 4
gpt4 key购买 nike

我正在使用下面的代码重置 $broadcast在每个测试用例之后,但似乎是 $rootScope.$broadcast.reset();不能正常工作,因为下面的测试应该返回 1,但它返回 6。

似乎原因是andCallThrough() ,因为之前我没有使用它 andCallThrough()函数,但经过一些重构后,它给了我一个错误 TypeError: Cannot read property 'defaultPrevented' of undefined ,所以我不得不使用来防止这个错误。

问题是我如何重置 broadcast使用时 andCallThrough还是有另一种更精确的方法?

beforeEach(function() {
spyOn($http, 'post');
spyOn($rootScope, '$broadcast').andCallThrough();
});

afterEach(function() {
$http.post.reset();
$rootScope.$broadcast.reset();
});

it('should make a POST request to API endpoint', function() {
$http.post.andCallThrough();
var response = { id: '123', role: 'employee', email: 'user@email.com', username: 'someUsername' };
$httpBackend.expectPOST(apiUrl + 'login').respond(response);
service.login();
$httpBackend.flush();
$timeout.flush();
expect($rootScope.$broadcast.callCount).toBe(1);
expect($rootScope.$broadcast).toHaveBeenCalledWith(AUTH_EVENTS.loginSuccess, response);
});

最佳答案

经过长时间调查这种情况下的工作方式,最终通过了测试,解决方案是当前的:

问题不在于重置广播()或 reset使用andCallThrough() 时,在每个测试用例之后不会调用方法。
问题在于$rootScope.$broadcast.andCallThrough();由其他事件和 .callCount() 触发函数返回 6 ,这基本上意味着 $broadcast spy 被叫了6次。就我而言,我只对 AUTH_EVENTS.loginSuccess 感兴趣事件并确保它只广播一次。

expect($rootScope.$broadcast.callCount).toBe(1);
expect($rootScope.$broadcast).toHaveBeenCalledWith(AUTH_EVENTS.loginSuccess, response);

从而挖掘 $rootScope.$broadcast.calls的方法给了我应该检索上述两个期望的所有调用的数组。因此,解决方案是:
it('should make a POST request to API endpoint', function() {
$http.post.andCallThrough();
var response = { id: '123', role: 'employee', email: 'user@email.com', username: 'someUsername' };
$httpBackend.expectPOST(apiUrl + 'login').respond(response);
service.login();
$httpBackend.flush();
$timeout.flush();

var loginSuccessTriggerCount = _($rootScope.$broadcast.calls)
.chain()
.map(function getFirstArgument(call) {
return call.args[0];
})
.filter(function onlyLoginSuccess(eventName) {
return eventName === AUTH_EVENTS.loginSuccess;
})
.value().length;

expect(loginSuccessTriggerCount).toBe(1);
});

关于angularjs - 使用 andCallThrough() 在每个测试用例之后重置广播(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28172194/

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