我正在测试一个调用服务(通过 goToPage 函数)的 Controller ,以便使用 spy 进行重定向。这很简单,但我收到“预期是 spy ,但得到了功能”。错误。我究竟做错了什么? 这是我的规范:
var createController,service scope;
beforeEach(inject(function($rootScope, $controller,$injector){
service = $injector.get('service ');
scope = $rootScope.$new();
createController = function() {
return $controller('controller', {
'$scope': scope
});
spyOn(service , ['redirect']).andCallThrough();
};
}));
describe('test if service is called', function() {
it('should call the service', function() {
var controller=createController();
scope.goToPage();
expect(service.redirect).toHaveBeenCalled();
});
});
});
最佳答案
首先,您在调用 return 后定义了 spy ,因此该代码永远不会运行。其次,在测试中定义您的 spy ,而不是在 beforeEach 中。
var createController,service scope;
beforeEach(inject(function($rootScope, $controller,$injector){
service = $injector.get('service ');
scope = $rootScope.$new();
createController = function() {
return $controller('controller', {
'$scope': scope
});
};
}));
describe('test if service is called', function() {
it('should call the service', function() {
var controller=createController();
spyOn(service , ['redirect']).andCallThrough();
scope.goToPage();
expect(service.redirect).toHaveBeenCalled();
});
});
关于unit-testing - SpyOn 返回预期是 spy ,但得到了函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33374812/