2

My component has:

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

  ngOnInit() {
    this.dataplanDetails.subscribe(res => {
      return this.parseSchema(res.details.submissionFileSchema)
    })
  }

  parseSchema(submissionFileSchema) {
    console.log('in parseSchema')
    const fileSchema = JSON.parse(submissionFileSchema)

My test is:

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;
    component['dataplanDetails'] = mockObservable
    fixture.detectChanges();
  }));

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

  it('should trigger a parseSchema event', () => {
    mockObservable.next({"details": { "submissionFileSchema": `{"properties": true, "layout": [true]}`}})
    spyOn(component, 'parseSchema').and.returnValue(true);
    expect(component.parseSchema).toHaveBeenCalled();
  })

The console.log triggers, so it's definitely in the parseSchema function. But the test fails with Expected spy parseSchema to have been called.

Shamoon
  • 41,293
  • 91
  • 306
  • 570

1 Answers1

2

You are setting up your spy after the observable will have triggered that code. Move your spy above where you are pushing your data onto your subject.

it('should trigger a parseSchema event', () => {
    spyOn(component, 'parseSchema').and.returnValue(true);
    mockObservable.next({"details": { "submissionFileSchema": `{"properties": true, "layout": [true]}`}})
    expect(component.parseSchema).toHaveBeenCalled();
})
Daniel W Strimpel
  • 8,190
  • 2
  • 28
  • 38