【问题标题】:AngularJS - How to mock a controller for a template?AngularJS - 如何模拟模板的控制器?
【发布时间】:2018-09-11 16:38:14
【问题描述】:

我有一个要测试的行为模板,但它使用我想避免的代码调用控制器,我宁愿为它注入一个模拟。我该怎么做?

我正在使用 Angular 1.7、Karma 和 Jasmine。

模板:

<div ng-controller="MyController">
    <span ng-if="(a && b) || (b && !c) || (!a && d)">
        {{ (b || a) + (d || c) }}
    </span>
</div>

控制器:

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')
    })

})

【问题讨论】:

    标签: angularjs angularjs-ngmock


    【解决方案1】:

    我发现我可以使用$controllerProvider.register 来覆盖控制器。

    beforeEach(module('App', function($controllerProvider) {
        $controllerProvider.register('MyController', function($scope) {
            $scope.mocked = true
        })
    }))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多