angular - 我如何为 ngOnInit 中的订阅编写单元测试用例?
问题描述
在这里,我订阅了单独文件(服务)中的数据
ngOnInit() {
this.service.getSelectedEvent.subscribe(
trendsPageEventListener => {
this.zone.run(()=>{
this.trendsPageEventListener = trendsPageEventListener;
});
});
}
解决方案
单元测试解决方案:
example.component.ts
:
import { Component, NgZone } from '@angular/core';
import { ExampleService } from './example.service';
@Component({})
export class ExampleComponent {
trendsPageEventListener: any;
constructor(private service: ExampleService, private zone: NgZone) {}
ngOnInit() {
this.service.getSelectedEvent().subscribe((trendsPageEventListener) => {
this.zone.run(() => {
this.trendsPageEventListener = trendsPageEventListener;
});
});
}
}
example.service.ts
:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable()
export class ExampleService {
getSelectedEvent(): Observable<string> {
return of('real trends page event listener');
}
}
example.component.spec.ts
:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { ExampleComponent } from './example.component';
import { ExampleService } from './example.service';
fdescribe('55234033', () => {
let exampleServiceSpy: jasmine.SpyObj<ExampleService>;
let component: ExampleComponent;
let fixture: ComponentFixture<ExampleComponent>;
beforeEach(() => {
exampleServiceSpy = jasmine.createSpyObj('ExampleService', [
'getSelectedEvent',
]);
exampleServiceSpy.getSelectedEvent.and.returnValue(
of('fake trend page event listener')
);
TestBed.configureTestingModule({
declarations: [ExampleComponent],
providers: [{ provide: ExampleService, useValue: exampleServiceSpy }],
});
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeDefined();
});
it('should pass', () => {
expect(component.trendsPageEventListener).toBeUndefined();
fixture.detectChanges();
expect(component.trendsPageEventListener).toBe(
'fake trend page event listener'
);
expect(exampleServiceSpy.getSelectedEvent).toHaveBeenCalledTimes(1);
});
});
测试结果:
推荐阅读
- python - 在一百万条记录上使用 pandas group by 的有效方法
- c# - C# Windows 窗体无法将数据重写到文件
- error-handling - 如何在唯一错误页面 html 中使用 Thymeleaf 开关管理 HTTPStatus
- javascript - 在状态对象中使用具有多个键/值对的 React Hooks
- ios - 是否可以通过接口生成器从超类更改约束的常量值?
- html - HTML代码在通知中间抛出一个空格问题
- python - 从文件中拆分字符串的问题
- python - 如何使用 pandas 从本地网络读取 csv 文件
- javascript - 在 ES6 的子超级方法中获取 js 类名
- azure - 我可以在 AKS 上使用 Azure 应用服务域吗?