(function () {
'use strict';
describe('TestButton', function () {
var controller, element, util;
beforeEach(function () {
module('app');
module('template');
module('TestUtil');
inject(function (TestUtilService) {
util = TestUtilService;
var testFunc = function foo(){
return 5;
};
// Passing the defined function to the custom directive and call it via
// controller.clickButton (it will be fired there)
// function=\' + testFunc + '" passing the function as string also not working
element = '<custom-button id="btn1" label="Click Me" function="testFunc"></custom-button>';
element = util.compileElement(element);
controller = util.getController(element, 'customButton');
});
});
it('should be resolved', function () {
expect(element.html()).toContain('input');
});
it('should be set', function () {
expect(element.find('input').val()).toBe('Click Me');
});
it('should be set', function () {
expect(element.find('input').attr('id')).toContain('button_btn1_');
});
it('should fire the passed function', function () {
//controller.clickButton() should log 5 or something, but its not working at all
//controller itself is working perfect (I have access to the whole directive-scope)
});
});
TestUtilService:
this.compileElement = function (element) {
var el = vm.$compile(element)(vm.$scope);
vm.$scope.$digest();
return el;
};
this.getController = function (element, directiveName) {
return element.controller(directiveName);
}
如何将对象传递给指令,编译并访问它。我也有传递数组或其他东西的问题。这在Karma / Jasmine中是如何工作的?
如果有人能给我一些提示,那会很棒。
答案 0 :(得分:0)
根据我的经验,你不能直接通过指令来做到这一点;但是,如果要添加函数(或对象)的功能,可以通过测试中使用的任何隔离范围对象来填充它。
然而,你不应断言它的存在。如果排除该功能,则激活自定义函数的测试将通过:
scope.testFunc = function(){console.log(1)};
element = '<custom-button id="btn1" label="Click Me"></custom-button>';
这是因为范围已经具有它关心的功能。
在这种情况下要做的一件事是设置一个条件,其中传递函数 并且假定它正在工作;实际上,您将注入该函数用于测试目的。在这一点上可能值得嘲笑,以确保它以你期望的方式触发,但超出此范围的断言不会有效。
答案 1 :(得分:-1)
您必须在Karma / Jasmine的创建范围内定义传递对象,如下所示:
scope.testFunc = function(){console.log(1)};
element = '<custom-button id="btn1" label="Click Me" function="testFunc"></custom-button>';