对 AngularJS(智能表)指令进行单元测试 [英] Unit testing an AngularJS (Smart Table) directive
问题描述
我正在使用智能表"并将使用他们的示例插件,其中复选框选择表中的一行:http://lorenzofox3.github.io/smart-table-website/#section-custom
I am working with "Smart Table" and will be using their example plugin where a checkbox selects a row in a table: http://lorenzofox3.github.io/smart-table-website/#section-custom
我正在为此指令编写单元测试,代码如下,这是失败的.有没有人为此代码编写过单元测试,或者可以帮助我指出我哪里出错了,以及我是否真的在测试正确的逻辑?
I am writing a unit test for this directive, code below, this is failing. Has anyone written a unit test for this code or could help direct me as to where I am going wrong and if I am actually testing the correct logic?
指令:
myApp.directive('csSelect', function () {
return {
require: '^stTable',
template: '',
scope: {
row: '=csSelect'
},
link: function (scope, element, attr, ctrl) {
element.bind('change', function (evt) {
scope.$apply(function () {
ctrl.select(scope.row, 'multiple');
});
});
scope.$watch('row.isSelected', function (newValue, oldValue) {
if (newValue === true) {
element.parent().addClass('st-selected');
} else {
element.parent().removeClass('st-selected');
}
});
}
};
});
单元测试:
describe('csSelect',function(){
var scope, element, attr, ctrl;
beforeEach(module('myApp.selectorresult'));
beforeEach(inject(function($rootScope, $compile) {
elm = angular.element(
'<td cs-select="row" class="ng-isolate-scope">' +
'<input type="checkbox">' +
'</td>');
scope = $rootScope;
$compile(elm)(scope);
scope.$digest();
}));
it('should create selectable input',function(){
console.log(elm.find('input'));
var checkbox = elm.find('input');
expect(checkbox.length).toBe(1);
});
});
推荐答案
对于仍然有此问题的任何人.我希望这有帮助.我为此苦苦挣扎了多年.我尝试模拟 stTableController,我尝试将供应商文件添加到 karma.conf.js 文件中,但无法通过任何测试.似乎当我删除 require: '^stTable' 时,测试将通过没有问题,但是有了它,所有测试都会失败.我无法删除它,因为这会破坏我的代码.
For anyone still having this issue. I hope this helps. I was struggling with this for ages. I tried mocking the stTableController, I tried adding the vendor files to the karma.conf.js files among other things but could not get any tests to pass. It seemed that when I removed the require: '^stTable' the tests would pass no problem, but with it in, all tests would fail. I couldn't remove this as this would break my code.
所以我最终发现我所要做的就是将 st-table 添加到我在 spec.js 文件中的元素中.
So what I finally found was that all I had to do was add st-table to my element in the spec.js file.
所以如果我的元素是var element = angular.element('<my-component></my-component');
我必须做到var element = angular.element('
So if my element was
var element = angular.element('<my-component></my-component');
I had to make it
var element = angular.element('<my-component st-table></my-component>');
在那之后,所有的测试都通过了.
After that, all tests were passing.
这篇关于对 AngularJS(智能表)指令进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!