例如,我有一个名为featureFlag
的自定义指令,它根据该功能的配置显示或隐藏元素:
<div *myFeatureFlag="'myFeatureName'">
This should be hidden if the myFeatureName feature is turned off.
</div>
然而,当谈到测试时,我很茫然。我已经知道如何测试指令本身,但我想测试*myFeatureFlag
是否添加到元素中,而不测试myFeatureFlag
指令内的逻辑。
有没有办法在单元测试中检查是否存在此指令?像这样:
it('should be wrapped in a feature flag', () => {
expect(element.querySelector('div').myFeatureFlag).toEqual("'myFeatureName'");
});
答案 0 :(得分:2)
这是一种丑陋的方式,但它有效。当Angular创建绑定时,它会向HTML添加一些注释
<!--template bindings={
"ng-reflect-my-feature-flag": "myFeatureName"
}-->
你能做的就是用一些正则表达式解析它并抓住JSON。然后只需检查值
function getFeatureFlagBinding(el: any) {
return JSON
.parse((/template bindings=(\{[\s\S]*?\})/g)
.exec(el.nativeElement.previousSibling.textContent)[1])['ng-reflect-my-feature-flag'];
}
it('should be wrapped in a feature flag', () => {
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
let el = fixture.debugElement.nativeElement;
let div = fixture.debugElement.queryAll(n => n.name === 'div')[0];
expect(getFeatureFlagBinding(div)).toBe('myFeatureName');
});