【问题标题】:Unit Test for setTimeOut in AngularAngular中setTimeOut的单元测试
【发布时间】:2021-09-25 18:33:41
【问题描述】:

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

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

【问题讨论】:

  • 欢迎来到 SO 社区,相信我!完成介绍性游览stackoverflow.com/tour 将对您和社区有益。这将有助于增加您获得帮助的机会。并且会给你一个徽章(:可能还有一些积分,这会给你更多的权限

标签: javascript angular unit-testing jasmine


【解决方案1】:

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 中的一种气味。可能有更好的解决方案。很难从这段简短的代码摘录中说出什么味道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2018-03-11
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多