如何解决茉莉花UNIT测试用例中的这种奇怪的随机错误?

问题描述

在运行jasmin单元测试用例时,我随机(一次3次)收到此错误,并且所有测试用例都失败了。

Cannot read property 'classList' of null\n    at <Jasmine>\n  at webpack:///path-to-component/component.ts:33:53 <- karma-test-shim.9578926fa4f5e11a1233db2d090778ef.bundle.js:226810:45263\n    at callSubscriberWithDelayedExceptions 

(webpack:///node_modules/pubsub-js/src/pubsub.js:62 <- karma-test-shim.9578926fa4f5e11a1233db2d090778ef.bundle.js:195654:13)\n    at deliverMessage (webpack:///node_modules/pubsub-js/src/pubsub.js:83 <- karma-test-shim.9578926fa4f5e11a1233db2d090778ef.bundle.js:195675:17)\n    at deliverNamespaced 

我知道这两个函数在这里有问题,但是我不确定在这里有什么问题?

ngOnInit(): void {
    this.aFunction();
    this.sub = PubSub.subscribe('someParam',(subId,Identifier: string) => {
      document.querySelector(Identifier).classList.add('highlight');
      setTimeout(() => {
        document.querySelector(Identifier).classList.remove('highlight');
      },2000);
    });
  }

  ngOnChanges(changes: SimpleChanges): void {
    this.aParam= false;
    /*  Few functions  */
  }

这里有两个涉及上述功能的测试用例

  it('should load without any input',() => {
    spyOn(document,'querySelector').and.callFake(function () {
      return {
        value: true,classList: {
          remove: () => { },add: () => { },}
      };
    });
    expect(component.customized).toBe(undefined);
  });


  it('should load with basic input attributes',() => {
    component.customized = { someEntity: true };
    spyOn(document,contains: () => { }
        }
      };
    });
    fixture.autoDetectChanges();
    componentInstance.ngOnChanges(null);
    fixture.whenStable().then(() => {
      expect(something).toBe(true);
    });
  });

我怀疑它与订阅有关,并且fakeAsync(我尚未应用)会导致其随机失败。

您能告诉我测试用例中有什么问题吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)