【发布时间】:2016-07-20 11:26:42
【问题描述】:
如何在 Angular 中测试指令中调用的作用域函数?
我在 Angular 版本 1 中使用 jasmine、karma runner 和 js 单元测试。
这是我的指令代码:
angular.module("myApp.directives")
.directive("test", ["$rootScope", function($rootScope) {
return {
restrict: "E",
scope: {
"figures": "="
},
templateUrl: "templates/components/test.html",
link: function(scope) {
scope.init = function() {
if (scope.figures !== undefined) {
for (let i = 0; i < scope.figures.length; i++) {
scope.figures[i].isModalVisible = false;
}
}
};
scope.init ();
}
};
}]);
这是我的单元测试:
describe("test", function () {
var element,
scope,
otherScope
mockData = [
{
isModalVisible: true
},
{
isModalVisible: false
}
];
beforeEach(angular.mock.module("myApp.directives"));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
scope.agg = mockData;
element = "<test figures=\"agg\"></test>";
element = $compile(element)(scope);
angular.element(document.body).append(element);
scope.$digest();
otherScope = element.isolateScope();
spyOn(otherScope, "init");
}));
//This one doesn't work
it("should close all modals by default", function () {
expect(otherScope.init).toHaveBeenCalled();
});
});
这是我目前得到的错误:“ Expected spy init to have been called。”
【问题讨论】:
标签: javascript angularjs unit-testing testing jasmine