Sunday, April 9, 2017

Angular 2 fakeAsync waiting for timeout in a function using tick()?

Leave a Comment

I'm trying to get the results from a mock backend in Angular 2 for unit testing. Currently, we are using fakeAsync with a timeout to simulate the passing of time.

current working unit test

it('timeout (fakeAsync/tick)', fakeAsync(() => {     counter.getTimeout();     tick(3000); //manually specify the waiting time })); 

But, this means that we are limited to a manually defined timeout. Not when the async task is completed. What I'm trying to do is getting tick() to wait until the task is completed before continuing with the test.

This does not seem to work as intended.

Reading up on the fakeAsync and tick the answer here explains that:

tick() simulates the asynchronous passage of time.

I set up a plnkr example simulating this scenario.

Here, we call the getTimeout() method which calls an internal async task that has a timeout. In the test, we try wrapping it and calling tick() after calling the getTimeout() method.

counter.ts

getTimeout() {   setTimeout(() => {     console.log('timeout')   },3000) } 

counter.specs.ts

it('timeout (fakeAsync/tick)', fakeAsync(() => {     counter.getTimeout();     tick(); })); 

But, the unit test fails with the error "Error: 1 timer(s) still in the queue."

Does the issue here in the angular repo have anything to do with this?

Is it possible to use tick() this way to wait for a timeout function? Or is there another approach that I can use?

2 Answers

Answers 1

I normally use the flushMicrotasks method in my unit tests for use with my services. I had read that tick() is very similar to flushMicrotasks but also calls the jasmine tick() method.

Answers 2

Try this bro:

// I had to do this: it('timeout (fakeAsync/tick)', (done) => {   fixture.whenStable().then(() => {        counter.getTimeout();        tick();     done();   }); }); 

Source

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment