how to mock ngModel?

北城余情 提交于 2019-12-11 13:17:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!