如何在ngOnInit内编写订阅的单元测试用例?

时间:2019-03-19 05:11:59

标签: angular unit-testing

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

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

2 个答案:

答案 0 :(得分:0)

这是针对JASMINE框架的。同样也可以用于玩笑。

上下文:在服务中为该方法创建一个存根并返回一个存根值。当您运行ngOnInit时,可观察对象将替换为您的存根值并由您的组件订阅。

在您的模拟服务中(最好在测试配置中注入模拟服务而不是真实服务),getSelectedEvent = jasmine.createSpy('getSelectedEvent');

在单元测试中,... mockService.getSelectedEvent.and.returnValue(of("any value"))... 然后运行Fixture.detectChanges(),它将在ngOnInit内部自动调用您的函数。

答案 1 :(得分:0)

单元测试解决方案:

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

测试结果:

enter image description here