我已经忍受了一段时间。我正在使用第三方列表框小部件(jqx-listbox)并尝试对其进行测试。一切正常ng serve
,甚至在 Chrome 中查看 Karma 输出时,我可以看到整个 UI、列表框和项目,这是我想要测试的。
问题是在测试中查询元素:
let openListbox = fixture.debugElement.query(By.css('.jqx-listitem-element'));
返回 null,而如果我在该行设置断点,并在 Chrome 控制台中使用 jQuery,$('.jqx-listitem-element)
则返回 DOM 元素!
如果我将测试中的查找更改为模板 () 中定义的元素,<jqxlistbox>
如下所示:let openListbox = fixture.debugElement.query(By.css('jqxlistbox'))
,这将返回 debugElement,我什至可以在该断点处检查该事物的本机元素,并查看其中是否包含内容,但无论我尝试了什么(返回该元素然后对其进行查询),我似乎都无法更深入地查询该对象,因此我的测试一直失败。
我也尝试过使用fakeAsync
,fixture.whenStable
但似乎完全跳过了(或者它永远不会稳定)。
这是小部件在运行时生成的渲染模板代码(这是我要检查的最里面的跨度)
<jqxlistbox _ngcontent-c0="" class="" style="" ng-reflect-attr-display-member="message" ng-reflect-attr-source="[object Object]"
ng-reflect-attr-value-member="errorType" ng-reflect-attr-width="100%">
<div class="ng-tns-c0-0 jqx-listbox jqx-reset jqx-rc-all jqx-widget jqx-widget-content jqx-disableselect" id="jqxWidgete238403f0fb8"
style="width: 100%; height: 200px;" aria-multiselectable="false" role="listbox" tabindex="1">
<div style="-webkit-appearance: none; background: transparent; outline: none; width:100%; height: 100%; align:left; border: 0px; padding: 0px; margin: 0px; left: 0px; top: 0px; valign:top; position: relative;">
<div style="-webkit-appearance: none; border: none; background: transparent; outline: none; width:100%; height: 100%; padding: 0px; margin: 0px; align:left; left: 0px; top: 0px; valign:top; position: relative;">
<div id="listBoxContentjqxWidgete238403f0fb8" style="-webkit-appearance: none; background: transparent; outline: none; border: none; padding: 0px; overflow: hidden; margin: 0px; left: 0px; top: 0px; position: absolute; width: 328px; height: 198px;">
<div style="outline: none 0px; overflow: hidden; width: 329px; position: relative; height: 404px;">
<div role="option" id="listitem0jqxWidgete238403f0fb8" class="jqx-listitem-element" style="height: 24px; top: 0px; left: 0px;"
aria-selected="true">
<span style="white-space: pre; display: block; visibility: inherit; width: 318px;" class="jqx-listitem-state-normal jqx-item jqx-rc-all jqx-listitem-state-selected jqx-fill-state-pressed">Open hard error</span>
</div>
</div>
</div>
</div>
</div>
</div>
</jqxlistbox>
编辑
我可以获得外部元素,它innerText
是该跨度的文本:“打开硬错误”,但这只是因为它是整个元素中唯一的文本节点。
使用这个测试代码,第一个断言通过,第二个断言失败,出现“无法读取 null 的属性 nativeElement”的错误,这对我来说太奇怪了,因为如果它可以找到 innerText,那么它就拥有整个 DOM 元素。我想知道查询查询返回的 DebugElement 是否有问题?:
fixture.detectChanges();
let openListbox = fixture.debugElement.query(By.css('#open jqxlistbox'));
expect(openListbox.nativeElement.innerText).toContain('Open hard error', 'item in listbox');
fixture.detectChanges();
let openListboxItem: HTMLElement = openListbox.query(By.css('span')).nativeElement;
expect(openListboxItem.textContent).toBe('Open hard error', 'item in listbox');