[英]AngularJS - How to mock a controller for a template?
I have a template with behavior I want to test, but it invokes a controller with code I'd like to avoid, and I'd rather inject a mock for it. 我有一个模板,该模板具有要测试的行为,但是它使用我要避免的代码来调用控制器,因此我希望为其注入一个模拟。 How do I do that?
我怎么做?
I am using Angular 1.7, Karma, and Jasmine. 我正在使用Angular 1.7,Karma和Jasmine。
Template: 模板:
<div ng-controller="MyController">
<span ng-if="(a && b) || (b && !c) || (!a && d)">
{{ (b || a) + (d || c) }}
</span>
</div>
Controller: 控制器:
app.controller('MyController', function($scope, MyService) {
$scope.a = (MyService.a || -MyService.d)
$scope.b = (MyService.b + MyService.c) || MyService.a
$scope.c = -MyService.c || (MyService.a + MyService.d)
$scope.d = -(MyService.a + MyService.d) - MyService.b
someOtherCode.IdontWantTo.exec()
})
describe('MyTemplate', () => {
let compile, $rootScope
beforeEach(inject(function($compile, $templateCache, _$rootScope_) {
compile = $compile($templateCache.get('MyTemplate.html'))
$rootScope = _$rootScope_
}))
it('should behave a certain way', () => {
const $scope = $rootScope.new()
const element = compile($scope)
$scope.a = 0
$scope.d = 3
$scope.$digest
expect(element.text()).toEqual('3')
})
})
I found I can use $controllerProvider.register
to override the controller. 我发现我可以使用
$controllerProvider.register
覆盖控制器。
beforeEach(module('App', function($controllerProvider) {
$controllerProvider.register('MyController', function($scope) {
$scope.mocked = true
})
}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.