我以前从来没有测试过我的angularjs指令,而且我为我现在的公司写的指令是使用事件来沟通指令和服务。
所以我写了一个指令,比如一个搜索指令。
<m-search />
这个指令广播"searchbox-valuechanged"
事件和键,现在我必须为它编写测试。
'use strict';
describe('<m-search>', function() {
beforeEach(module('hey.ui'));
var rootScope;
beforeEach(inject(function($injector) {
rootScope = $injector.get('$rootScope');
spyOn(rootScope, '$broadcast');
}));
it("should broadcast something", function() {
expect(rootScope.$broadcast).toHaveBeenCalledWith('searchbox-valuechanged');
});
});
输入
<input class="m-input m-input--no-border" type="search" placeholder="Search"
ng-model="ctrl.searchValue"
ng-model-options="{debounce: 100}"
ng-change="ctrl.onChange({search: ctrl.searchValue})">
调用指令控制器
中的一个方法vm.onChange = function (searchValue) {
$rootScope.$broadcast('searchbox-valuechanged', {data: searchValue});
};
如何测试广播?
我是这样做的…
describe('m-search directive', function() {
var ctrl, // your directive's controller
$rootScope; // a reference to $rootScope
beforeEach(function() {
// bootstrap your module
module('hey.ui');
inject(function($compile, _$rootScope_) {
$rootScope = _$rootScope_;
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject#resolving-references-underscore-wrapping-
// create an instance of your directive
var element = $compile('<m-search></m-search')($rootScope.$new());
$rootScope.$digest();
// get your directive's controller
ctrl = element.controller('mSearch');
// see https://docs.angularjs.org/api/ng/function/angular.element#methods
// spy on $broadcast
spyOn($rootScope, '$broadcast').and.callThrough();
});
});
it('broadcasts searchbox-valuechanged on change', function() {
var searchValue = {search: 'search string'};
ctrl.onChange(searchValue);
expect($rootScope.$broadcast).toHaveBeenCalledWith(
'searchbox-valuechanged', {data: searchValue});
});
});
你会注意到这根本不依赖于指令的模板。我不认为模板功能属于单元测试的范畴;这个问题最好留给量角器测试。单元测试是关于测试组件的API,以确保它们做它们应该做的事情。