Function within setTimout has not been called in Unit Test

Published

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());    
  }

MY UNIT TEST

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

    }))
  });

When karma runs shows me those resuls:

enter image description here

Can you help me identifying whats going wrong?

Source: Angular Questions

Published
Categorized as angular, jasmine, karma-jasmine, settimeout, unit-testing Tagged , , , ,

Answers

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';

Laurianne Grady

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq