问题
So I am testing a controller, which is referencing a property specified as ngModel in DOM. But while I am testing my controller, I don't have the template. So whenever $scope.foo.property is being accessed in the controller, it throws an error.
回答1:
In your test, you can define your property before instantiate your controller :
it('should mock ng-model', inject(function($rootScope, $controller) {
$rootScope.foo = {
property: 'mock value'
};
$controller('myController', {$scope: $rootScope});
})));
回答2:
Controllers and views (templates) are two separate things in Angular applications. What glues them together is the scope (or model). So, to test a controller all you need is a fake scope to pass to the controller function.
Here's a very simple example using a global controller (just to keep things easier to understand - don't use global controllers in production code) and a pseudo test function:
function MyCtrl($scope) {
$scope.bar = $scope.foo.property + 1;
}
function test() {
var scope = { foo: { property: 1 }};
MyCtrl(scope);
expect(scope.bar).toBe(2);
}
It gets a little bit more complicated than that when the controller is defined within an module, but that's another story.
来源:https://stackoverflow.com/questions/17977139/how-to-mock-ngmodel