[英]by.css always returns null [jasmine unit test ]
我不知道为什么在我的 Angular 项目中,当我尝试访问 HTML 元素时,Jasmin 总是返回 null!
it('should find the <p> with fixture.debugElement.query(By.css)', () => {
const bannerDe: DebugElement = fixture.debugElement;
const paragraphDe = bannerDe.query(By.css('p'));
const p: HTMLElement = paragraphDe.nativeElement;
expect(p.textContent).toEqual('banner works!');
});
<p class="title">banner works!</p>
我也曾尝试调用 'fixture.whenStable().then' 但它再次返回 null!
it('should find the <p> with fixture.debugElement.query(By.css)', () => {
const fixture = TestBed.createComponent(MobileAppLinkComponent);
fixture.detectChanges();
fixture.whenStable().then(() => {
const bannerDe: DebugElement = fixture.debugElement;
const paragraphDe = bannerDe.query(By.css('p'));
const p: HTMLElement = paragraphDe.nativeElement;
expect(p.textContent).toEqual('banner works!');
})
p
标签很可能被*ngIf
隐藏了。 您可以尝试注销fixture.nativeElement
以查看是否看到p
标签吗?
it('should find the <p> with fixture.debugElement.query(By.css)', () => {
const bannerDe: DebugElement = fixture.debugElement;
// !! Add this line to see if the p tag is there
console.log(fixture.nativeElement);
const paragraphDe = bannerDe.query(By.css('p'));
const p: HTMLElement = paragraphDe.nativeElement;
expect(p.textContent).toEqual('banner works!');
});
如果p
标签不存在,很可能它被父元素的*ngIf
隐藏了。 您必须使此条件为真,然后 fixture.detectChanges fixture.detectChanges()
以便 HTML 更新,然后尝试使用fixture.debugElement.query(By.css('p'))
获取p
标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.