微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 11 中的 DebugElement、By.css、nativeElement 和.querySelector

如何解决Angular 11 中的 DebugElement、By.css、nativeElement 和.querySelector

下面的代码来自下面的链接https://angular.io/guide/testing-components-basics#bycss

服务器端渲染器可能不支持完整的 HTML 元素 API。 如果它不支持 querySelector,之前的测试可能会失败。

DebugElement 提供适用于所有受支持查询方法 平台。

  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!');
  });

我的问题:

1 在非浏览器上使用 DebugElement.query(By.css('p')) 能否避免异常?

2 下面的 'should have <p> with "banner works!"''should find the <p> with fixture.debugElement.nativeElement)' 的测试用例是否会导致非浏览器异常?

@Component({
  selector: 'app-banner',template: `<p>banner works!</p>`,styles: []
})
export class BannerComponent { }


import { DebugElement } from '@angular/core';
import { ComponentFixture,Testbed,waitForAsync } from '@angular/core/testing';

import { By } from '@angular/platform-browser';
import { BannerComponent } from './banner-initial.component';


describe('BannerComponent (with beforeEach)',() => {
  let component: BannerComponent;
  let fixture: ComponentFixture<BannerComponent>;

  beforeEach(() => {
    Testbed.configureTestingModule({declarations: [BannerComponent]});
    fixture = Testbed.createComponent(BannerComponent);
    component = fixture.componentInstance;
  });

  it('should create',() => {
    expect(component).tobedefined();
  });

  it('should contain "banner works!"',() => {
    const bannerElement: HTMLElement = fixture.nativeElement;
    expect(bannerElement.textContent).toContain('banner works!');
  });

  it('should have <p> with "banner works!"',() => {
    const bannerElement: HTMLElement = fixture.nativeElement;
    const p = bannerElement.querySelector('p');
    expect(p.textContent).toEqual('banner works!');
  });


  it('should find the <p> with fixture.debugElement.nativeElement)',() => {
    const bannerDe: DebugElement = fixture.debugElement;
    const bannerEl: HTMLElement = bannerDe.nativeElement;
    const p = bannerEl.querySelector('p');
    expect(p.textContent).toEqual('banner works!');
  });

  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!');
  });
});

解决方法

是的,您的两个测试用例都可以在非浏览器上运行。确认您可以使用 ChromeHeadless 浏览器运行测试用例。您可以在此处https://developers.google.com/web/updates/2017/04/headless-chrome#tldr 阅读有关无头 chrome 的更多信息。 要使用无头 chrome,您需要使用 karma.conf.js

更改您的 browsers: ['ChromeHeadless'] 文件

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。