admin管理员组文章数量:1183211
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 ]
})pileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(AsyncComponent);
component = fixtureponentInstance;
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.
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.
4 Answers
Reset to default 10As 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');
}));
});
I had this problem, I'm surprised nobody looked up any real solution.
Possible solutions
- Your template might not be rendered in your test, especially if you are overriding it. So, the | async operation won't trigger.
- You aren't using
fixture.detectChanges()
enough to allow template rendering. Rendering occurs after OnInit stage. So make sure you use fixture.detectChanges at least 2 times. - Maybe you have
setTimeout
operations pending, for exampledebounce(100)
would require atick(100)
to resolve (within a fakeAsync test).
Cheers
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.
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();
本文标签: javascriptAngular testing async pipe does not trigger the observableStack Overflow
版权声明:本文标题:javascript - Angular testing async pipe does not trigger the observable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738307219a2073884.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论