我在几个地方搜索以获得有关这方面的想法。
How do I unit test $scope.broadcast, $scope.$on using Jasmine
$scope.$on not working in Jasmine SpecRunner
我认为它有所帮助,但似乎我仍然缺少一些东西。我试图在代码中测试一个$ rootScope。$ on的控制器。所以在单元测试中我试图触发$ broadcast,所以$ on得到它并且代码运行。但是我目前的代码无效。
这是我的控制器:
{
"BrowseNodeId":[
"11608080011"
],
"Name":[
"Quadcopters & Multirotors"
],
"Ancestors":[
{
"BrowseNode":[
{
"BrowseNodeId":[
"166583011"
],
"Name":[
"RC Vehicles"
],
"Ancestors":[
{
"BrowseNode":[
{
"BrowseNodeId":[
"6925830011"
],
"Name":[
"RC Vehicles & Parts"
],
"Ancestors":[
{
"BrowseNode":[
{
"BrowseNodeId":[
"276729011"
],
"Name":[
"Hobbies"
],
"Ancestors":[
{
"BrowseNode":[
{
"BrowseNodeId":[
"165795011"
],
"Name":[
"Categories"
],
"IsCategoryRoot":[
"1"
],
"Ancestors":[
{
"BrowseNode":[
{
"BrowseNodeId":[
"165793011"
],
"Name":[
"Toys & Games"
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
},
{
"BrowseNodeId":[
"3226142011"
],
"Name":[
"Grown-Up Toys"
],
"Children":[
{
"BrowseNode":[
{
"BrowseNodeId":[
"3226143011"
],
"Name":[
"Action & Toy Figures"
]
},
{
"BrowseNodeId":[
"3226145011"
],
"Name":[
"Die-Cast & Toy Vehicles"
]
},
{
"BrowseNodeId":[
"3226146011"
],
"Name":[
"Games"
]
},
{
"BrowseNodeId":[
"3226148011"
],
"Name":[
"Novelty & Gag Toys"
]
},
{
"BrowseNodeId":[
"3226149011"
],
"Name":[
"Puzzles"
]
},
{
"BrowseNodeId":[
"5483953011"
],
"Name":[
"Executive Desk Toys"
]
}
]
}
],
"Ancestors":[
{
"BrowseNode":[
{
"BrowseNodeId":[
"165795011"
],
"Name":[
"Categories"
],
"IsCategoryRoot":[
"1"
],
"Ancestors":[
{
"BrowseNode":[
{
"BrowseNodeId":[
"165793011"
],
"Name":[
"Toys & Games"
]
}
]
}
]
}
]
}
]
}
这是我的测试:
constructor($state: ng.ui.IStateService, store: angular.a0.storage.IStoreService, jwtHelper: angular.jwt.IJwtHelper, $rootScope: any) {
this.currentDate = new Date();
this.state = $state;
this.store = store;
this.jwtHelper = jwtHelper;
this.userFullname = '';
$rootScope.$on('$stateChangeStart',
(event: any, toState: any, toParams: any, fromState: any, fromParams: any, error: any) => {
var jwtToken = this.store.get('token');
if (jwtToken != null) {
var decodedToken: any = this.jwtHelper.decodeToken(jwtToken);
}
});
}
两个间谍都说他们从未被召唤过。我错过了什么?
答案 0 :(得分:2)
不是测试事件侦听器是否被触发,而是验证是否触发了注册侦听器的代码。
它被解雇了,但是controllerScope.$on
函数调用了beforeEach
,而不是it
。 spyOn
无法触及过去以检测先前的函数调用;即使它,这可能不是你试图做的考验。
基本上你做过这样的事情:
window.addEventListener('mouseMove', someFunctionExpr);
spyOn(window, 'addEventListener');
triggerMouseMoveEvent();
expect(window.addEventListener).toHaveBeenCalled();
我无法与decodeToken
/ jwt
通话 - 您的代码在任何地方都没有引用它,所以我不知道在哪里可以调用它。
答案 1 :(得分:0)
如果您想测试该事件是否广播,请执行spyOn(scope, '$broadcast').and.callThrough();
如果你想测试控制器的逻辑,将它包装在一个函数中并与$broadcast
/ $on
分开测试(毕竟你没有测试Angular的事件传递机制)。