0
votes

I have tried to test Angular component by using Karma/Jasmine. To be frank I don't have much idea about karma/jasmine and while testing getting error like "Uncaught TypeError: Cannot read property 'coSearchCriteria' of undefined thrown". But normal component functionality is working fine. If any idea please help me.

This is my Testing code, Here basic 'should create' test case is working but 2nd one giving error.

describe('SearchPanelComponent', () => {
  let component: SearchPanelComponent;
  let fixture: ComponentFixture<SearchPanelComponent>;
  

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule, HttpModule, CarbonDatepickerModule, CarbonModalModule,CarbonIconModule, StoreModule.forRoot({})],
      declarations: [ SearchPanelComponent, UploadsearchcriteriaComponent ],
      providers: [ Store, StoreModule, CustomerorderService,ConnectionBackend, ApiConnectorService, HttpClient, HttpHandler,Http, CarbonModalService]    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SearchPanelComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

it('RSSD To should be invalid', async( () => {
  const dateValue = component.orderUnitForm.controls['rssddateto'];
  dateValue.setValue('12-02/2012');
  fixture.detectChanges();
  expect(component.orderUnitForm.valid).toEqual(false);
}));

And 'coSearchCriteria' I have used at .ts file only like this

this.store.select(selectorCOCriteriaState)
    .subscribe((coSearchCriteria: SearchCriteriaState) => {   
       this.searchState = coSearchCriteria.lastUsedCriteria;     
    });   
    if(this.searchState){
        this.fillSearchStateData();  
    }
1
Are you sure that's the only place? When an error talks about of undefined, it usually means you're trying to read it from an undefined parent. In this case, it's being passed in, so you're not referencing any parent.user184994
user184994 Thanks for reply, Yes that is the only place I have used 'coSearchCriteria' in my class.Roy
You can add schemas: [NO_ERRORS_SCHEMA], if you are unsure about it and want to get rid of it. My guess is that it could be from child components of SearchPanelComponent. Also be warned that adding NO_ERROR_SCHEMA would hide other errors as well.Amit Chigadani
@AmitChigadani Tried but no use, I am getting error while doing testing only, normal functionality working fine.Roy
Can you also add minimal template and ts code that could be problematic?Amit Chigadani

1 Answers

2
votes

Finally got the fix, Just need to mock the ngrx store in spec file.

class MockStore {
  public dispatch(obj) {
    console.log('dispatching from the mock store!')
  }

  public select(obj) {
    console.log('selecting from the mock store!');

    return Observable.of({})
  }
}