Search code examples
angularjasminetddkarma-runner

Issue with jasmine test cases in Angular for conditional data


I'm learning to write the test cases in jasmine for angular app ,I have a component in my html as follows

<app-image [imgData]="pageData['configData']['image']"></app-image>

and my test case is as below

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PlainTextPipe } from '@pipes/plain-text.pipe';
import { DataService } from '@services/data.service';

import { BasicComponent } from './basic.component';

fdescribe('BasicComponent', () => {
  let component: BasicComponent;
  let fixture: ComponentFixture<BasicComponent>;
  let pageData;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [BasicComponent],
      providers: [PlainTextPipe]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BasicComponent);
    component = fixture.componentInstance;
    spyOn(component, 'renderPage');

    fixture.detectChanges();
  });


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





  it('should initialize', () => {
    component.ngOnInit();
    fixture.detectChanges();
  });

});

when i run this test case i get Cannot read property 'image' of undefined as in certain scenario i dont have an image how can i handle it in my test case as in particular scenario i will have the image and in other case i wont as this is the common component


Solution

  • The issue is that pageData.configData is undefined.

    Try:

    it('should create', () => {
        component.pageData.configData.image = 'hello'; // not sure if it's a string but you know how to mock it
        expect(component).toBeTruthy();
      });