单元测试 angular 和茉莉花

Unit testing angular and jasmine

如何在 index.html 文件的 angular 中进行单元测试?

例如:我想创建一个单元测试来检查 body 标签是否分配了特定的 class。这可能吗

大多数单元测试或规范文件都是为组件制作的,但我似乎无法访问 body 标签。

这是针对组件内部任何内容的有效 css 单元测试,只是不知道如何访问 index.html 页面的 body 标签。


  it('should have class-name in body class tag', () => {
    const fixture = TestBed.createComponent(AppComponent);

    fixture.detectChanges();
    const compiled = fixture.debugElement;

    expect(compiled.query(By.css('.class-name'))).toBeTruthy();
  });

您可以通过 document 访问正文元素,然后检查元素 className 属性是否具有预期的 class 名称。

这里是stackblitz showing a functional example.

describe("Integration::AppComponent", () => {
  let component;
  let fixture;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent        
      ]
    });
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it("should set a class on the body element", () => {
    const body = document.body;
    expect(body.className).toContain('my-class');
  });
});

下面是我的小示例组件如何设置正文样式。

export class AppComponent  {
  ngOnInit(){
    document.body.className += ' my-class';
  }
}

请注意 - 如果您使用 Angular Universal 之类的东西,当您的组件在服务器上 运行 时,document 将不可用。