gpt4 book ai didi

angular - 无法读取 Angular Testing 模拟的属性 'subscribe'

转载 作者:太空狗 更新时间:2023-10-29 17:20:00 25 4
gpt4 key购买 nike

我正在尝试对具有注入(inject)服务的 Angular 组件进行单元测试。在组件的构造函数中,调用了注入(inject)服务的一个方法,该方法返回一个 Observable。我试图在组件的单​​元测试中模拟该服务,但我一直遇到此错误:TypeError: Cannot read property 'subscribe' of undefined

我尝试通过以下方式模拟该服务:

const serviceStub = {
getObservable: () => { return {subscribe: () => {}}; },
};

beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
{provide: MyService, useValue: serviceStub}
]
})


it('should create', () => {
spyOn(serviceStub, 'getObservable').and.returnValue({subscribe: () => {}});
expect(component).toBeTruthy();
});

感觉好像遗漏了一些明显的东西。有人可以指出吗?

更新

即使我在我的测试平台提供商中注入(inject)实际服务,我也会收到此错误。

组件的构造函数看起来像这样:

private _subscription: Subscription;

constructor(private _service: MyService) {
this._subscription = _service.getObservable().subscribe(console.log);
}

最佳答案

使用 inject 注入(inject)服务并模拟它而不是 stub

it('should create', inject([MyService], (myService: MyService) => {
spyOn(myService, 'getObservable').and.returnValue({subscribe: () => {}});
expect(component).toBeTruthy();
}));

这里是完整版:

组件:

@Component({
selector: 'my-cmp',
template: 'my cmp {{x}}'
})
export class MyComponent {
x;

constructor(private myService: MyService) {
this.myService.getObservable()
.subscribe(x => {
console.log(x);
this.x = x;
});
}
}

测试:

   describe('my component test', () => {
let fixture: ComponentFixture<MyComponent>, comp: MyComponent, debugElement: DebugElement, element: HTMLElement;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [MyService]
});
}));

beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
comp = fixture.componentInstance;
debugElement = fixture.debugElement;
element = debugElement.nativeElement;
});

it('should create', inject([MyService], (myService: MyService) => {
expect(comp).toBeTruthy();
}));

it('should set value', async(inject([MyService], (myService: MyService) => {
spyOn(myService, 'getObservable').and.returnValue(Observable.of(1));

fixture.detectChanges();

fixture.whenStable().then(() => {
expect(comp.x).toEqual(1);
});
})));
});

关于angular - 无法读取 Angular Testing 模拟的属性 'subscribe',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43796727/

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