简体   繁体   中英

Unit Test for setTimeOut in Angular

I just start learn new things about unit test in Angular. I have read some article, but I am still stuck when I implement create test case for setTimeOut condition. I have function in .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.

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 . 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.

PS: setTimeout is a smell in Angular. There could be a better solution. It's difficult to say what is smelling from this short code excerpt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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