[英]Getting TypeError pipe is not a function while testing angular component using observable with declarative approach using async
[英]Angular testing async pipe does not trigger the observable
我想测试一个使用异步管道的组件。 这是我的代码:
@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');
});
但是测试失败了。 似乎出于某种原因,Angular 不会对 Observable 执行。 我缺少什么?
当我尝试使用do
运算符记录 observable 时,我在浏览器控制台中看不到任何输出。
据我所知,您不能将fakeAsync
与异步管道一起使用。 我很想被证明是错误的,但我尝试了一段时间,但什么也做不了。 相反,使用async
实用程序(我将其别名为realAsync
以避免与async
关键字混淆)并await
Promise 包装的setTimeout
而不是使用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');
}));
});
我遇到了这个问题,我很惊讶没有人找到任何真正的解决方案。
可能的解决方案
fixture.detectChanges()
不足以允许模板渲染。 渲染发生在 OnInit 阶段之后。 所以请确保您至少使用 fixture.detectChanges 2 次。setTimeout
操作,例如debounce(100)
需要一个tick(100)
来解决(在 fakeAsync 测试中)。干杯
您可以尝试以下方法:
it('should emit values', (done) => {
component.number.subscribe((numberElement) => {
expect(numberElement).toBe(0);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.number')).nativeElement.innerHTML).toBe('0');
done();
});
});
每当观察到新元素被观察时,您可以订阅它并检查价值和模板是否符合您的期望。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.