我为angular2组件编写了测试,它使用ng-inline-svg模块来加载我的svg文件.在编写实际组件之后,事实证明该组件运行良好,但测试失败.我怀疑测试不会等待svg插入完成.有没有办法解决它?测试失败:
it('Should create new svg element',async(()=>{ fixture.detectChanges(); expect(de.query(By.css('svg'))).toBeTruthy(); }));
如果我用’div’替换’svg’选择器,它会发现包装器没有问题.
解决方法
编辑:
这是一个已知的错误:https://github.com/angular/angular/issues/15164
By.css()无法选择SVGElement实例.
您应该能够使用DOMElement.querySelector方法获取对SVG元素的引用.
it('Should create new svg element',async(()=>{ fixture.whenStable().then(() => { const nativeElement = de.nativeElement; fixture.detectChanges(); expect(nativeElement.querySelector('svg')).toBeTruthy(); }); }));
plunker:https://embed.plnkr.co/bgH31O/
原始答案:
我不知道ng-inline-svgmodule的实现细节,但也许< svg>元素是异步插入DOM的吗?
如果是这种情况,您可以使用whenStable():
it('Should create new svg element',async(()=>{ fixture.whenStable().then(() => { fixture.detectChanges(); expect(de.query(By.css('svg'))).toBeTruthy(); }); }));
引用文档
In fact,the whenStable promise resolves when all pending asynchronous activities within this test complete—the definition of “stable.”