And*_*van 19 testing jasmine angular
我在 Angular 中进行单元测试时遇到错误。错误是 TypeError: 无法读取未定义的属性“pipe”。为此,我使用了可观察的对象,并尝试测试订阅的输出。我将不胜感激任何帮助!谢谢你!
obs1$: Observable<number>;
pos=12345;
constructor(
private service1: Service) {
}
ngOnInit() {
this.obs1$ = this.service1.retrieveData1(this.pos)
.pipe(
map(item => item.value || null))
}Run Code Online (Sandbox Code Playgroud)
let component: ComponentName;
let fixture: ComponentFixture<ComponentName>;
const serviceSpy = jasmine.createSpyObj('Service',['retrieveData1']);
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ComponentName],
providers: [{ provide:Service, useValue: {} }
})
.overrideComponent(ComponentName, {
set: {
providers: [
{ provide: ComponentName, useValue: serviceSpy }
]
}
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ComponentName);
component = fixture.componentInstance;
});
fit('should retrieve value', done => {
component.pos = 12345;
fixture.detectChanges();
component.obs1$.subscribe(value => {
expect(value).toEqual(1);
done();
})
})Run Code Online (Sandbox Code Playgroud)
<div *ngIf="obs1$ | async as obs">
<div [ngSwitch]="obs" class="col-2 p-0">
<div *ngSwitchCase="0">
<p>red</p>
</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
小智 27
创建间谍后,您还需要返回一个虚拟/模拟可观察值。
代码需要一个 Observable 所以你可以尝试下面的方法(在每个它调用服务的块中你可以添加这个)
serviceSpy.retrieveData1.and.returnValue(of('mock value as requires'))
Run Code Online (Sandbox Code Playgroud)
或者你可以像这样模拟服务
let serviceSpy= jasmine.createSpyObj('Service', {
'retrieveData1': of('mock data'),
'other': 'some val'
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47909 次 |
| 最近记录: |