4

I'm trying to write Angular test using jest :

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [BookListComponent],
    }).compileComponents();
  }));

When i launched :

npm run test:watch 

I got this error :

error TS2304: C annot find name 'async'.

Khaled Boussoffara
  • 1,567
  • 2
  • 25
  • 53

2 Answers2

5

You have to change async to waitForAsync in Angular 11 because they changed it. They changed it because the async you import from @angular/core/testing in previous versions is similar to the native async of JavaScript and could cause confusion.

import { waitForAsync } from '@angular/core/testing';
.....
beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [BookListComponent],
    }).compileComponents();
  }));

Link for waitForAsync.

AliF50
  • 16,947
  • 1
  • 21
  • 37
  • 1
    thanks, now i'm trying to understand why async is replace with waitForAsync – Khaled Boussoffara Dec 02 '20 at 20:03
  • If you're still wondering, this answer explains it: https://stackoverflow.com/a/64704028/7365461 – AliF50 Dec 02 '20 at 20:54
  • 1
    "In Angular 10.1.0, waitForAsync() has replaced async() to avoid confusion, but is otherwise exactly the same. Any documentation you see that discusses using async() will also apply to waitForAsync(). async() has been marked as deprecated and will be removed entirely in version 12." ok thank you so much – Khaled Boussoffara Dec 02 '20 at 21:00
  • I now understand why my colleague warned me to use angular. I spent the last hour trying to find the proper way of awaiting asyncs, I found `async () => function`, I found `async(() => function)`, I found injectAsync and finally I found waitForAsync. Honest question: How do you keep track of those changes? – Samuel Dec 14 '20 at 19:48
  • @Samuel https://blog.ninja-squad.com/2020/09/03/what-is-new-angular-10.1/ I guess you can look at blogs or look at the documentation of Angular itself. The beauty of TypeScript is that it will show you that async is marked for deprecation or that async can't be imported and then you will do research what happened to async in Angular testing and will most likely come to it was removed for waitForAsync. Unfortunately (or it could also be fortunately) most if not all JavaScript frameworks go through changes like this. – AliF50 Dec 14 '20 at 20:19
2

async is a not a function. Try it like this:

beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [BookListComponent],
    }).compileComponents();
  });

I'm not to sure if you would even need to mark the function as async because you don't use the await inside your before each.

Have a look at the documentation

AliF50
  • 16,947
  • 1
  • 21
  • 37
Erbsenkoenig
  • 1,584
  • 14
  • 18