首页 > 解决方案 > 玩笑:测试组件和布尔值以显示加载器

问题描述

我正在学习 Jest 来测试组件和逻辑的东西。

这是我要测试的组件:

import {Component, Input} from @angular/core;

@Component({
  selector: "nsnet-bouton-download",
template: `
   <div>
    <nsnet-inline-loader *ngIf="isDocumentLoading"></nsnet-inline-loader>
    <button [ngClass]="{'is-not-loading': !isDocumentLoading}">Download</button>
   </div>
  `
})

export class ButtonDownloadComponent {
  @Input() isPdfLoading: boolean = false;  
}

这是我到目前为止写的测试:

import {BoutonTelechargerComponent} from "../../../../main/frontend/common-ng2/component/bouton-telecharger";
import {InlineLoaderComponent} from "../../../../main/frontend/common-ng2/component/loader/inline-loader.component";

describe("Le composant BoutonTelechargerComponent", () => {

  let component: BoutonTelechargerComponent;
  component = new BoutonTelechargerComponent();

  const loader = new InlineLoaderComponent();
  const isPdfLoading = component.isDocumentLoading;



  describe("est bien créé", () => {

    it("sans erreur(s)", () => {
      expect(component).toBeDefined();
    });
  });
});

我想知道如何测试显示加载器的布尔值,我应该测试 ngClass 吗?谢谢

标签: angularjestjs

解决方案


您可以直接测试布尔值,如下所示:

it("should show the loader", () => {
   // setting up component data 
   expect(component.isDocumentLoading).toBeTrue(); // if its loading
   expect(component.isDocumentLoading).toBeFalse(); // if its false
});

您还可以使用以下命令检查组件nsnet-inline-loader是否在 dom 中呈现fixture.debugElement

it("should render nsnet-inline-loader ", () => {
   // setting up component data 
   const ele = fixture.debugElement.query(By.css('nsnet-inline-loader'));
   expect(ele).toBeTruthy(); // if it should be present
   expect(ele).toBeFalsy(); // if it should be absent
});

如果你想测试给定的类是否被渲染,你可以这样做:

it("should renderd button with class", () => {
   // setting up component data 
   const ele = fixture.debugElement.query(By.css('.is-not-loading'));
   expect(ele).toBeTruthy(); // if it should be present
   expect(ele).toBeFalsy(); // if it should be absent
});

但是测试课程取决于您的要求。但是如果你要测试这两种情况,那就有点多余了。

你也有isDocumentLoadinghtml 和isPdfLoading. 应该是某种错误,需要相同。


推荐阅读