Shamoon
Shamoon

Reputation: 43639

How do I unit test with a subscribe in Angular5?

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"])

This is my component. It has a subscribe that I'm having trouble unit testing. My test includes:

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 = {}
  // })
});

I'm getting an error: Failed: undefined is not an object (evaluating 'this.dataplanDetails.subscribe')

How do I trigger the subscribe from the test?

Upvotes: 2

Views: 546

Answers (2)

GettingStarted
GettingStarted

Reputation: 7625

Angular 2 RC5 Testing Promises in ngOnInit Not Working

I feel like testing if the subscription is defined should be enough, or you might trigger the loadingObservable to switch isLoading to either true or false.

If you're using loadingObservable try to switch to isLoading and set it to true/false

Upvotes: 0

bc1105
bc1105

Reputation: 1270

1) Pull the subscribe callback into it's own method and test it directly.

2) Mock the emission of dataplanDetails. Ex:

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

Upvotes: 2

Related Questions