【问题标题】:Perform ngx-spinner unit testing执行 ngx-spinner 单元测试
【发布时间】:2019-11-13 05:36:21
【问题描述】:

我在我的组件上使用ngx-spinner 在某个远程调用过程的页面上显示加载指示符。在我的组件上,我有以下 ngx spinner 代码:

<ngx-spinner [fullScreen]="true" type="ball-clip-rotate" size="medium" bdColor="rgba(51,51,51,0.1)" color="grey">
</ngx-spinner>

在页面加载时的 init 组件中,我正在显示微调器,如下所示:"

  constructor(
    private spinner: NgxSpinnerService) {

  }

  ngOnInit() {

    this.spinner.show();

在我对服务器进行远程调用之后,当这项工作完成后,我将隐藏微调器。

我的目标是创建相同的单元测试,即当页面加载时,我需要确保微调器显示在页面上。为此,我编写了以下测试用例:

  it('should show loading indicator if the page is not loaded', () => {

    // pageLoaded should be try because the form will be loaded only when that is true based on ng if

    const element = getElementByTag('ngx-spinner');

    //What to write here?

  });

我在测试中获得了该元素,但我无法检测它是否可见。我试过 element.nativeElement.visible 但它返回为 null。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    我首先要说的是,在单元测试的上下文中,一般的经验法则是每个组件都应该单独测试。这意味着您不需要检查微调器本身是否显示,您只需要检查是否确实调用了 show() 方法。你可以通过监视 NgxSpinnerService 来实现这一点:

      it('should show loading indicator if the page is not loaded', () => {
        const spinnerSpy = spyOn(TestBed.get(NgxSpinnerService), "show");
        expect(spinnerSpy).toHaveBeenCalled();
      });
    

    话虽如此,我注意到当显示微调器时,&lt;ngx-spinner&gt;&lt;/ngx-spinner&gt; 标记中插入了一个 div。因此,如果其子项的长度为 1,则您可以判断它正在显示:

      it('should show loading indicator if the page is not loaded', () => {
        // pageLoaded should be try because the form will be loaded only when that is true based on ng if
        const element = getElementByTag('ngx-spinner');
        //What to write here?
        expect(element.children.size).toBe(1);
      });
    

    【讨论】:

    • 感谢分享,我注意到单元测试 ngx spinner 的一个问题,在 init 上来自 componenet ng 的 ngx spinner show 正在让 spinner 出现在 ng test karma jasmine 页面上,如何防止该加载程序出现在 ng 测试页面上?
    • 如果你选择了以前的单元测试方法,你应该可以通过mock show方法来达到你的目的:spinnerSpy.and.returnValue(null)。把它放在期望调用之前。您还可以为 NgxSpinnerService 类提供模拟。
    猜你喜欢
    • 2021-10-04
    • 2012-03-28
    • 2022-01-25
    • 1970-01-01
    • 2021-01-30
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多