首页 > 解决方案 > Angular中setTimeOut的单元测试

问题描述

我刚开始学习有关 Angular 中单元测试的新知识。我已经阅读了一些文章,但是当我为 setTimeOut 条件实现创建测试用例时我仍然卡住了。我在 .component.ts 中有功能

  resetDropdown(elementId) {
    setTimeout(() => {
      if (elementId !== 'free-text-head-'.concat(this.id)) {
        if (elementId !== this.id) {
          if (this.isFreeTextEnabled && elementId !== 'free-text-body-'.concat(this.id)) {
            this.isFreeTextEnabled = false;
            this.assignSearchKeywowrd(this.value, this.config.displayKeyMain, this.config.selectedKey);
            this.isFreeTextSearchEmpty = false;
            this.listData = this.options;
          }
        }
      }
    }, 100);
  }

我如何在茉莉花中创建这个?谢谢你们的帮助

标签: javascriptangularunit-testingjasmine

解决方案


fakeAsync+tick非常方便。

describe('#resetDropdown when isFreeTextEnabled is true and argument is nor 'free-text-head-'.concat(component.id), nor 'free-text-body-'.concat(component.id), nor component.id', ()=>{
   const mockOptions = {someOption: 'someValue'};
   beforeEach(() => fakeAsync({
      component.options = mockOptions;
      component.isFreeTextEnabled = true;
      component.id = 'something not similar to argument';

      component.resetDropdown('something not similar to component.id');
      tick(100);
   }))
   it(`sets isFreeTextEnabled to false`, () => {
      expect(component.isFreeTextEnabled).toEqual(false)
   });
   it(`sets isFreeTextSearchEmpty to false`, () => {
      expect(component.isFreeTextSearchEmpty).toEqual(false)
   });
   it(`sets component.listData to component.options`, () => {
      expect(component.listData).toEqual(mockOptions)
   });
});

在一个中只保留一个期望是一种有用的做法it。当测试失败时,可以很容易地识别出什么是错误的。当有几行类似expect(something).toEqual(true)并且失败消息说expected false to be true需要时间来找出expects 中的哪一个失败时。

PS:setTimeout是Angular中的一种气味。可能有更好的解决方案。很难从这段简短的代码摘录中说出什么味道。


推荐阅读