Reputation: 2077
I want to test a component that uses the async pipe. This is my code:
@Component({
selector: 'test',
template: `
<div>{{ number | async }}</div>
`
})
class AsyncComponent {
number = Observable.interval(1000).take(3)
}
fdescribe('Async Compnent', () => {
let component : AsyncComponent;
let fixture : ComponentFixture<AsyncComponent>;
beforeEach(
async(() => {
TestBed.configureTestingModule({
declarations: [ AsyncComponent ]
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(AsyncComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should emit values', fakeAsync(() => {
tick(1000);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('div')).nativeElement.innerHTML).toBe('0');
});
But the test failed. It's seems Angular does not execute to Observable from some reason. What I am missing?
When I'm trying to log the observable with the do
operator, I don't see any output in the browser console.
Upvotes: 28
Views: 16556
Reputation: 179
You have to include AsyncPipe
in the imports of your component as well as in the declarations of the TestBed
:
import { AsyncPipe } from '@angular/common';
@Component({
selector: 'test',
imports: [ AsyncPipe ]
template: `
<div>{{ number | async }}</div>
`
})
class AsyncComponent {
number = Observable.interval(1000).take(3)
}
TestBed.configureTestingModule({
declarations: [ AsyncComponent, AsyncPipe ]
}).compileComponents();
Upvotes: 0
Reputation: 5188
The solution is very simple as pointed by delpo already, you have to call fixture.detectChanges()
before tick()
because without initial render template will not load, hence async pipe is not triggered.
it('should emit values', fakeAsync(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges(); // call this initially as well before tick
tick(1000);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('div')).nativeElement.innerHTML).toBe('0');
discardPeriodicTasks();
}));
Also don't use setTimeout
because this will actually delay your test with 1 second, I know 1 second may not matter for few people but imagine you have n
no of test, that will delay the test every 1 second or whatever the time you have provided.
For these type of tests angular introduced fakeAsync
which wraps all the async operations including setTimeout
and setInterval
and when tick is called it fast-forward the time without needing to actually wait.
Upvotes: 0
Reputation: 239
I had this problem, I'm surprised nobody looked up any real solution.
Possible solutions
fixture.detectChanges()
enough to allow template rendering. Rendering occurs after OnInit stage. So make sure you use fixture.detectChanges at least 2 times.setTimeout
operations pending, for example debounce(100)
would require a tick(100)
to resolve (within a fakeAsync test).Cheers
Upvotes: 2
Reputation: 749
As far as I can tell, you can't use fakeAsync
with the async pipe. I would love to be proven wrong, but I experimented for a while and couldn't get anything to work. Instead, use the async
utility (which I alias as realAsync
to avoid confusion with the async
keyword) and await
a Promise-wrapped setTimeout
instead of using tick
.
import { async as realAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { AsyncComponent } from './async.component';
function setTimeoutPromise(milliseconds: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
}
describe('AsyncComponent', () => {
let component: AsyncComponent;
let fixture: ComponentFixture<AsyncComponent>;
let element: HTMLElement;
beforeEach(realAsync(() => {
TestBed.configureTestingModule({
declarations: [ AsyncComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AsyncComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
fixture.detectChanges();
});
it('should emit values', realAsync(async () => {
await setTimeoutPromise(1000);
fixture.detectChanges();
expect(element.getElementsByTagName('div')[0].innerHTML).toEqual('0');
}));
});
Upvotes: 10