首页 > 解决方案 > 我如何为 ngOnInit 中的订阅编写单元测试用例?

问题描述

在这里,我订阅了单独文件(服务)中的数据

ngOnInit() {
    this.service.getSelectedEvent.subscribe(
        trendsPageEventListener => {
            this.zone.run(()=>{
                this.trendsPageEventListener = trendsPageEventListener; 
               });
        });       
  }

标签: angulartypescriptunit-testing

解决方案


单元测试解决方案:

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);
  });
});

测试结果:

在此处输入图像描述


推荐阅读