繁体   English   中英

Angular 中 setTimeOut 的单元测试

[英]Unit Test for setTimeOut in Angular

我刚刚开始学习有关 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);
  }

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

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 是一种有用的做法。 当测试失败时,可以很容易地识别出问题所在。 当有几行像expect(something).toEqual(true)并且失败消息说expected false to be true ,需要时间来找出expect s 中的哪一个失败。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM