我无法成功测试我的angular.js指令(业力+茉莉花)......
基本上,在我的指令编译功能中,我用表格替换元素内容
后进行单元测试时scope = $rootScope;
element = angular.element('<my-directive></my-directive>');
$compile(element)($rootScope);
scope.$digest();
我希望找到包含我的表单的元素,用&#39; ... abc ......&#39; ...
事实并非如此......: - (
这是我的(简化)指令:
angular.module('myApp')
.directive('myDirective', function() {
return {
restrict: 'E',
scope: {},
compile: function(element) {
element.replaceWith('<form> ... abc ... </form>');
}
};
});
这是我的测试:
describe('Directive: paypalButton', function () {
beforeEach(angular.mock.module('myApp'));
var element, scope;
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope;
element = angular.element('<my-directive></my-directive>');
$compile(element)($rootScope);
scope.$digest();
}));
it('replaced content should contain abc', function() {
expect(element.html()).toContain('abc');
});
});
该指令有效(在浏览器中我看到&#39; abc&#39;),但&#34;期望&#34;测试总是失败:我没有得到&#39; abc&#39;在元素的html()中,但总是得到xyz&#39; ...
我确定我错过了一些明显的东西......: - (
答案 0 :(得分:2)
我会把测试写成如下。演示PLUNKER
describe('Directive: paypalButton', function () {
var element, scope, $compile;
beforeEach(function(){
module('myApp');
inject(function ($rootScope, $compile) {
scope = $rootScope;
element = angular.element('<my-directive></my-directive>');
$compile(element)(scope);
});
});
it('replaced content should be abc', function() {
element.scope().$digest();
expect(element.text()).toEqual(' ... abc ... ');
});
});
指令中的此更改:
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {},
compile: function(element) {
element.append('<form> ... abc ... </form>');
}
};
});
注意: -
append()
。element.scope().$digest();
。