我有我要测试的AngularJS中的这段代码:
var _savePendingChanges = function() {
try {
$rootScope.$broadcast('externalSave');
} catch (e) {
// Sometimes, AngularJS throws a "Cannot read property $$nextSibling of
// null" error. To get around this we must use $apply().
$rootScope.$apply(function() {
$rootScope.$broadcast('externalSave');
});
}
}
这里是我到目前为止编写的测试,它无法正常工作(它抛出了errorMessage
中的错误和Jasmine错误:Error: Expected function to throw an Error.
):
fit('should save pending changes', function() {
var errorMessage = 'Cannot read property $$nextSibling of null';
spyOn($rootScope, '$broadcast').and.throwError(errorMessage);
expect(function() {
RouterService.savePendingChanges();
}).toThrowError(errorMessage);
});
有人可以帮我吗?谢谢!
您可以检查广播是否被两次调用:
fit('should save pending changes', function () {
var errorMessage = 'Cannot read property $$nextSibling of null';
var broadcastSpy = spyOn($rootScope, '$broadcast').and.throwError(errorMessage);
RouterService.savePendingChanges();
expect(broadcastSpy).toHaveBeenCalledTimes(2);
});