Dof*_*ofs 63 unit-testing angularjs
我有一个控制器在根镜上发出广播事件.我想测试broacast事件是否正确触发.
我的控制器中的代码如下所示:
$scope.$watch("pageIndex", function(){
if($scope.pageIndex == 4)
{
// emit social share
$rootScope.$broadcast('myEvent');
}
});
Run Code Online (Sandbox Code Playgroud)
我试图用以下代码测试它:
it('Should call myEvent when pageIndex is 4',function(){
scope.pageIndex = 4;
scope.$apply();
expect(rootScope.$on).toHaveBeenCalledWith('myEvent');
});
Run Code Online (Sandbox Code Playgroud)
但是它告诉我代码没有被调用,我已经手动测试了它.然后我尝试使用以下代码:
it('Should call myEvent when pageIndex is 4',function(){
var listener = jasmine.createSpy('listener');
rootScope.$on('myEvent', listener);
scope.pageIndex = 4;
scope.$apply();
expect(listener).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
但同样的负面结果.有没有办法测试一个事件是否被广播?
Mik*_*ugh 117
假设您正在使用Jasmine,以下内容对我来说非常有用.
... other unit test setup code ...
var rootScope;
beforeEach(inject(function($injector) {
rootScope = $injector.get('$rootScope');
spyOn(rootScope, '$broadcast');
}));
describe("my tests", function() {
it("should broadcast something", function() {
expect(rootScope.$broadcast).toHaveBeenCalledWith('myEvent');
});
});
Run Code Online (Sandbox Code Playgroud)
如果您正在广播消息并将对象附加到消息上,您甚至可以测试对象是否符合预期
someObj = { ... something ... };
expect(rootScope.$broadcast).toHaveBeenCalledWith('someEvent', someObj);
Run Code Online (Sandbox Code Playgroud)
Sud*_*r N 11
这是它如何用mochaJs完成的,其中sinon用于模拟和chai用于期望.
describe("broadcast test", function() {
beforeEach(inject(function($rootScope){
sinon.spy($rootScope, "$broadcast")
scope.foo() //this broadcasts the event. $rootScope.$broadcast("testEvent")
}))
it("broadcasts the event", inject(function($rootScope){
expect($rootScope.$broadcast.calledWith("testEvent")).to.be.true
}))
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32284 次 |
最近记录: |