简体   繁体   English

Angular 中 setTimeOut 的单元测试

[英]Unit Test for setTimeOut in Angular

I just start learn new things about unit test in Angular.我刚刚开始学习有关 Angular 单元测试的新知识。 I have read some article, but I am still stuck when I implement create test case for setTimeOut condition.我已经阅读了一些文章,但是当我为 setTimeOut 条件实现创建测试用例时,我仍然卡住了。 I have function in .component.ts我在 .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);
  }

How I do create this one in jasmine?我如何在茉莉花中创建这个? Thank you guys for your help谢谢你们的帮助

fakeAsync + tick are very handy for this. 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's a useful practice to keep only one expect in one it .it只保留一个 expect 是一种有用的做法。 Makes it easy to recognize what is wrong when a test fails.当测试失败时,可以很容易地识别出问题所在。 When there are several lines like expect(something).toEqual(true) and the failure message says expected false to be true it takes time to find out which one among the expect s fails.当有几行像expect(something).toEqual(true)并且失败消息说expected false to be true ,需要时间来找出expect s 中的哪一个失败。

PS: setTimeout is a smell in Angular. PS: setTimeout是 Angular 中的一种味道。 There could be a better solution.可能有更好的解决方案。 It's difficult to say what is smelling from this short code excerpt.很难说这段简短的代码摘录有什么味道。

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

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