我正在使用这个结构:
使用ControllerAs的指令。 Controller对服务执行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
并结合其他东西,但没有任何作用。有什么建议吗?
答案 0 :(得分:0)
尝试使用scope.mockController.things而不是mockController.things。