我正在尝试使用Jasmine对AngularJS指令进行单元测试.该指令旨在使用D3js在postLink阶段将SVG元素添加到模板中.这在实际应用中很好用.
在单元测试中,似乎D3代码永远不会被执行.
angular.module('app',[]); angular.module('app').directive('d3Test',function () { return { template: '<div id="map"></div>',restrict:'E',scope: { someAttr: '@',},link: function postLink(scope,element,attrs) { d3.select('#map').append('svg'); } }; });
这是单元测试:
describe('directive test',function () { var element,scope; beforeEach(module('app')); beforeEach(inject(function ($rootScope,$compile) { scope = $rootScope.$new(); element = '<d3-test></d3-test>'; element = $compile(element)(scope); scope.$apply(); })); it('should have an SVG child element',function () { expect(element.html()).toEqual('<div id="map"><svg></svg></div>'); }); });
我收到的错误是:
PhantomJS 1.9.8 (Mac OS X) directive test should have an SVG child element Failed Expected '<div id="map"></div>' to equal '<div id="map"><svg></svg></div>'.
我对如何测试D3将进行的DOM更改的期望是错误的吗?
我怎样才能最好地测试这个?
解决方法
问题很简单.
d3.select方法在window.document中搜索元素.
在您的测试用例中,您的元素位于分离的dom元素中,而不是window.document的一部分.
d3.select方法在window.document中搜索元素.
在您的测试用例中,您的元素位于分离的dom元素中,而不是window.document的一部分.
要解决此问题,您可以直接通过指令的元素获取节点,而不是使用全局选择器.
d3.select(element.find('div#map')[0]).append('svg');
注意:此代码适用于角度jQuery.如果你不在项目中使用jQuery,你可能需要调整选择器,因为那时你只能通过标签名称进行查找.
https://docs.angularjs.org/api/ng/function/angular.element