xzegga
xzegga

Reputation: 3149

Function within setTimout has not been called in Unit Test

I trying to test an angular 10 function that call another function within a setTimeout. I am using Karma and Jasmine but I can get to pass the test. I read a lot of examples on blog post, angular documentation and even here in stackoverflow and all points me to this solution:

MY METHOD

  loadDefault() {
    ... do something
    setTimeout(this.run, 100);    
  }

MY UNIT TEST

  describe('loadDefault', () => {
    it('should call run function after ...', fakeAsync(() => {
      
      const spyRun = spyOn(component, 'run').and.callFake(fakeFn);
      component.loadDefault()   
      tick(101);  
      fixture.detectChanges()
      expect(spyRun).toHaveBeenCalled()

    }))
  });

When karma runs shows me those resuls:

enter image description here

Can you help me identifying whats going wrong?

Upvotes: 1

Views: 344

Answers (1)

emmanuel agarry
emmanuel agarry

Reputation: 355

Try This. I only added the tick function to your code. You can get the tick function from angular core testing modules

 describe('loadDefault', () => {
    it('should call run function after ...', fakeAsync(() => {
      
      const spyRun = spyOn(component, 'run').and.callFake(fakeFn);
      component.loadDefault() 
      tick(500)    
      fixture.detectChanges()
      expect(spyRun).toHaveBeenCalled()

    }))
  });

Don't forget to import tick from "@angular/core/testing".

Your import should look something like this

import { async, ComponentFixture, TestBed, tick } from '@angular/core/testing';

Upvotes: 1

Related Questions