【问题标题】:AngularJS changing controller mocksAngularJS 更改控制器模拟
【发布时间】:2015-01-29 09:11:02
【问题描述】:

我正在使用这个结构:

带有 ControllerAs 的指令。 控制器依赖于执行 REST 请求的服务。

指令和控制器:

angular.module('app')
.directive('thingsList', function () {
    return {
        templateUrl: 'thingsListEntry-template.html',
        restrict: 'A',
        controller: 'thingsListController as ctrl'
    };
})
.controller('thingsListController', function (thingsStorage) {
    thingsStorage.getList().then(angular.bind(this, function (response) {
        this.things = response;
    }));
});

我现在要做的是用控制器模拟测试指令:

describe('things list test suite', function() {

describe('tests for the directive', function () {
    var scope, render, element, mockController;

    /**
     * Mock the controller
     */
    beforeEach(module('app', function ($provide, $controllerProvider) {
        $controllerProvider.register('thingsListController', function () {
            this.things = [];
            mockController = this;
        });
    }));

    beforeEach(inject(function($rootScope, $compile) {
        scope = $rootScope.$new();
        var angularElement = angular.element('<div things-list></div>');
        var compileFunction = $compile(angularElement);
        render = function () {
            element = compileFunction(scope);
            $rootScope.$digest();
        };
    }));

    it('should be empty without things', function() {
        render();
        expect(element[0].querySelectorAll('div.things-list-entry').length).toEqual(0);
    });

接下来我想做的是更改控制器模拟中的things 并对其进行测试。我不知道该怎么做

it('should contain 1 entry with 1 thing', function () {
        mockController.things = [{'name':'1'}];
        render();
        expect(element[0].querySelectorAll('div.thing-list-entry').length).toEqual(1);
    });

我在这里设置 mockController.things,但我不确定如何访问 mockController。上面的版本在模拟设置中设置它。我还尝试使用scope.ctrl.things 和其他一些东西,但没有任何效果。有什么建议吗?

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive


    【解决方案1】:

    尝试使用 scope.mockController.things 而不是 mockController.things。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 2015-03-15
      相关资源
      最近更新 更多