gpt4 book ai didi

angular - 类型错误 : Cannot read property 'pipe' of undefined (jasmine, Angular )

转载 作者:行者123 更新时间:2023-12-04 13:09:53 25 4
gpt4 key购买 nike

我有一个关于 Angular 单元测试的错误。错误是类型错误:无法读取未定义的属性“管道”。为此,我使用了一个 observable 并尝试测试订阅的输出。我将不胜感激任何帮助!谢谢!

  obs1$: Observable<number>;
pos=12345;

constructor(
private service1: Service) {
}

ngOnInit() {

this.obs1$ = this.service1.retrieveData1(this.pos)
.pipe(
map(item => item.value || null))

}
 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();
})
})
<div *ngIf="obs1$ | async as obs">
<div [ngSwitch]="obs" class="col-2 p-0">
<div *ngSwitchCase="0">
<p>red</p>
</div>
</div>
</div>

最佳答案

创建 spy 后,您还需要返回一个虚拟/模拟 observable 值。
代码期待一个 Observable 所以下面的方法你可以尝试(在每个 it 块中你可以添加这个调用服务)

serviceSpy.retrieveData1.and.returnValue(of('mock value as requires'))
或者你可以模拟这样的服务
let serviceSpy= jasmine.createSpyObj('Service', {
'retrieveData1': of('mock data'),
'other': 'some val'
});

关于angular - 类型错误 : Cannot read property 'pipe' of undefined (jasmine, Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66600829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com