question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItΒ collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Test fails with flush() but works with tick()

See original GitHub issue

🐞 bug report

Affected Package

The issue is caused by package @angular/core/testing

Is this a regression?

I dont know.

Description

I have a simple component:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { asyncScheduler, Observable, of, queueScheduler, scheduled } from 'rxjs';

@Component({
  selector: 'test-component',
  templateUrl: './test-component.component.html'
})
export class TestComponentComponent implements OnInit {
  value: string;

  constructor() { }

  ngOnInit(): void {
    const data$ = this.fetchDataScheduler();

    data$
      .subscribe(value => {
        this.value = value;
      });
  }

  private fetchDataScheduler(): Observable<string> {
    return scheduled(of('foo'), asyncScheduler);
  }

}

and two simple tests:

Passing:

it('async - test setTimeout', fakeAsync(() => {
    expect(component.value).toBeFalsy();
    fixture.detectChanges(); // ngOnInit
    expect(component.value).toBeFalsy();
    tick();
    expect(component.value).toBe('foo');
  }));

Failing:

it('async - test setTimeout', fakeAsync(() => {
    expect(component.value).toBeFalsy();
    fixture.detectChanges(); // ngOnInit
    expect(component.value).toBeFalsy();
    flush();
    expect(component.value).toBe('foo');  // <- fails here
  }));

I think that the test with flush() should pass too, according to documentation:

Simulates the asynchronous passage of time for the timers in the fakeAsync zone by draining the macrotask queue until it is empty. The returned value is the milliseconds of time that would have been elapsed.

πŸ”¬ Minimal Reproduction

Stackblitz or GitHub

🌍 Your Environment

Angular Version:


Angular CLI: 8.3.20
Node: 12.11.1
OS: win32 x64
Angular: 8.2.14
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.802.2
@angular-devkit/build-angular      0.802.2
@angular-devkit/build-optimizer    0.802.2
@angular-devkit/build-webpack      0.802.2
@angular-devkit/core               8.2.2
@angular-devkit/schematics         8.3.20
@angular/cdk                       8.2.3
@angular/cli                       8.3.20
@angular/flex-layout               8.0.0-beta.27
@angular/material                  8.2.3
@angular/material-moment-adapter   8.2.3
@ngtools/webpack                   8.2.2
@schematics/angular                8.3.20
@schematics/update                 0.803.20
rxjs                               6.5.4
typescript                         3.5.3
webpack                            4.38.0

Anything else relevant? Discussed on SO

and here, where Netanel suggests that it is caused by periodic tasks not being flushed with flush().

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:3
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
JiaLiPassioncommented, Mar 10, 2020

@felikf , this is not a bug because in your code you use asyncScheduler which is in fact a setInterval which is a periodic macroTask, and currently the flush() API only flush non-periodic macroTasks such as setTimeout(), so for now, please use tick() to make it work, and I am currently working on adding new APIs to make this work easily. Thanks.

2reactions
thw0rtedcommented, Nov 17, 2020

@JiaLiPassion is there any status update on the β€œnew APIs” you mentioned in your comment above? rxjs AsyncTask is the default scheduler for a lot of observables, and because it uses setInterval under the hood – even for observables that run once – it’s currently impossible to flush them.

Read more comments on GitHub >

github_iconTop Results From Across the Web

What is the difference between tick() and flush() in angular ...
This unit test shows that all async tasks should be finished when it returns, and that the returned value tells you how long...
Read more >
Angular testing: flush vs. flushMicrotasks - Damir's Corner
The test can be fixed by using flushMicrotasks instead of flush : it("should add a toast", fakeAsync(() => { const toastsService = TestBed....
Read more >
API Reference | Vitest
skipIf(isDev)('prod only test', () => { // this test only runs in production }) ... stockFailed - it may return any falsy value,...
Read more >
Asynchronous work - Jasmine Documentation
beforeEach(async function() { await someLongSetupFunction(); }); it('does a ... to be more error-prone, but it can be useful for testing callback-based codeΒ ...
Read more >
fakeAsync - Angular
Timers are synchronous; tick() simulates the asynchronous passage of time. ... describe('this test', () => { it('looks async but is synchronous',Β ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found