【发布时间】:2016-02-10 09:59:18
【问题描述】:
我正在尝试测试调用回调的逻辑,作为参数传递给指令。
我的指令是这样启动的:
var directive = {
...
scope: {
onSave: '&'
},
controller: 'TmpViewCtrl',
controllerAs: 'vm',
bindToController: true // Isolate scope
};
在控制器中,我使用将其存储为 vm 变量(John Pappas 样式指南)
function TmpViewCtrl($scope) {
var vm = this;
$scope.save = save;
function save(element) {
if (element !== undefined) {
vm.onSave({element: element});
}
}
在我的测试中,我使用了以下 beforeEach:
var dataMock = {
onSave: function (elem) {
return true;
},
beforeEach(inject(function (_$compile_, _$rootScope_, _$controller_) {
$compile = _$compile_;
$rootScope = _$rootScope_.$new();
$controller = _$controller_('TmpViewCtrl', {$scope: $rootScope}, dataMock);
// Compile a piece of HTML containing the directive
element = $compile("<div tmp-view ></div>")($rootScope);
// fire all the watches, so the scope expressions will be evaluated
$rootScope.$digest();
}));
我的测试看起来像
it('If save is triggered, callback should be called', function () {
// Check that the compiled element contains the templated content
var temp = {test: "test"};
spyOn($rootScope, "save");
spyOn($controller, "onSave");
$rootScope.save(temp);
expect($rootScope.save).toHaveBeenCalled();
expect($controller.onSave).toHaveBeenCalled();
});
控制器的最后一行说
Expected spy onSave to have been called.,但它应该被调用吗?或者我正在检查错误的控制器范围?
【问题讨论】:
标签: angularjs unit-testing angularjs-directive jasmine