【问题标题】:How do I unit test with a subscribe in Angular5?如何在 Angular5 中通过订阅进行单元测试?
【发布时间】:2018-04-09 15:41:23
【问题描述】:
import { Component, Input, OnInit } from '@angular/core';
import {DataplansDetails} from '../../models/dataplans-details';
import * as _ from "lodash";

@Component({
  selector: 'jsonform',
  templateUrl: './jsonform.component.html',
  styleUrls: ['./jsonform.component.scss']

})
export class JsonformComponent implements OnInit {
  @Input() dataplanDetails: any;
  public layout: any = [];
  public schema: any = {};

  ngOnInit() {
    this.dataplanDetails.subscribe(res => {
      const fileSchema = JSON.parse(res.details.submissionFileSchema)

      const formLayout = fileSchema["layout"]
      this.schema = {
        type: "object",
        properties: fileSchema["properties"]
      }

      const schemaKeys = Object.keys(this.schema["properties"])

这是我的组件。它有一个subscribe,我在单元测试中遇到了麻烦。我的测试包括:

fdescribe('JsonformComponent', () => {
  let component: JsonformComponent;
  let fixture: ComponentFixture<JsonformComponent>;
  const mockObservable = new Subject();

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      providers: [
        {provide: Store, useClass: StoreStub}
      ],
      imports: [],
      declarations: [JsonformComponent]
    }).compileComponents();
  }));

  beforeEach(async(() => {
    fixture = TestBed.createComponent(JsonformComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component['dataplanDetals'] = mockObservable
  }));

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  fit('should not set layout if there are no properties', () => {
    mockObservable.next({test: 'data'})


    component.parseSchema('{"layout": [], "properties": {}}')
    // component.properties = false
    expect(component.schema).toEqual({})
    expect(component.layout).toEqual([])
  })

  // it('should set the layout to have the keys', () => {
  //   component.properties = {}
  // })
});

我收到一个错误:Failed: undefined is not an object (evaluating 'this.dataplanDetails.subscribe')

如何从测试中触发订阅?

【问题讨论】:

    标签: angular unit-testing observable


    【解决方案1】:

    1) 将subscribe回调拉到自己的方法中,直接测试。

    2) 模拟dataplanDetails 的发射。例如:

    const mockObservable = new Subject();
    component['dataplanDetails'] = mockObservable;
    mockObservable.next({ test: 'data' });
    ...now you should hit the `subscribe` block
    

    【讨论】:

    • 仍然没有点击subscribe。另外,在ngOnInit 中,console.log(this.dataplanDetails) 返回undefined
    • beforeEach 块中设置@Input()。您可能还需要在那里显式调用ngOnInit
    • ngOnInit 似乎是自动调用的。如何设置@Input()
    • 通过在ngOnInit 运行之前在组件上设置dataplanDetails 的值。这是我的第二个例子。
    • 我更新了我原来的帖子。这是你描述的吗?
    【解决方案2】:

    Angular 2 RC5 Testing Promises in ngOnInit Not Working

    我觉得测试是否定义了订阅就足够了,或者您可能会触发 loadingObservable 将 isLoading 切换为 true 或 false。

    如果您正在使用 loadingObservable,请尝试切换到 isLoading 并将其设置为 true/false

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      相关资源
      最近更新 更多