Mat*_*eod 18 jasmine angularjs karma-runner
我想测试以下函数实际上是使用jasmine初始化该控制器.似乎使用间谍是要走的路,它只是没有按照我期望的那样工作,因为我把它的预期称为"它"块.我想知道是否有一种特殊的方法可以检查是否在调用范围函数中调用了某些内容,而只是在控制器本身中调用.
App.controller('aCtrl', [ '$scope', function($scope){
$scope.loadResponses = function(){
//do something
}
$scope.loadResponses();
}]);
Run Code Online (Sandbox Code Playgroud)
// spec文件
describe('test spec', function(){
beforeEach(
//rootscope assigned to scope, scope injected into controller, controller instantiation.. the expected stuff
spyOn(scope, 'loadResponses');
);
it('should ensure that scope.loadResponses was called upon instantiation of the controller', function(){
expect(scope.loadResponses).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
您需要使用您创建的范围自行初始化控制器.问题是,您需要重新构建代码.你不能监视不存在的函数,但是在调用函数之前你需要spyOn.
$scope.loadResponses = function(){
//do something
}
// <-- You would need your spy attached here
$scope.loadResponses();
Run Code Online (Sandbox Code Playgroud)
由于你不能这样做,你需要在$scope.loadResponses()其他地方拨打电话.
成功监视范围函数的代码是这样的:
var scope;
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
$controller('aCtrl', {$scope: scope});
scope.$digest();
}));
it("should have been called", function() {
spyOn(scope, "loadResponses");
scope.doTheStuffThatMakedLoadResponsesCalled();
expect(scope.loadResponses).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
在控制器实例化之前(在 beforeEach 中)设置间谍是测试实例化时执行的控制器功能的方法。
编辑:还有更多内容。正如注释所指出的,该函数在 ctrl 实例化时不存在。要监视该调用,您需要在拥有作用域之后、实例化控制器之前,在设置块中为变量分配任意函数(在本例中,您将 scope.getResponses 分配给空函数)。然后您需要编写间谍(再次在您的设置块中并在 ctrl 实例化之前),最后您可以实例化控制器并期望对该函数进行调用。抱歉最初的回答很糟糕