Mr.M
Mr.M

Reputation: 1490

Jasmine / Karma error as cannot read property of undefined

I am trying to create cover all the line (Jasmine / Karma) but I am getting the error as Cannot read property 'search' of undefined

Here is my code for component code.

public search() {
  if (this.searchCompany.length) {
    let term = this.searchCompany;
    this.tempList = this.tempNameList.filter(tag => {
      if (tag.companyName.toLowerCase().indexOf(term.toLowerCase()) > -1) {
        return tag;
      }
    });
  } else {
    this.resetCompanies();
  }
}

Here is the below code for spec which I tried:

it('should search the data', () => {
  component.search;
  expect(component.search()).toBeUndefined();
});

What I am doing wrong here?

Upvotes: 2

Views: 13817

Answers (1)

shokha
shokha

Reputation: 3189

Since your search method has if statement - we can write at least two unit tests.

This one is for case when there is no search tag - we expect that resetCompanies will be called if we have empty searchCompany:

  it('should resetCompanies if search is empty', () => {
    component.searchCompany = '';
    spyOn(component, 'resetCompanies').and.callFake(() => null);

    component.search();

    expect(component.resetCompanies).toHaveBeenCalled();
  });

And this one is for case when we have search tag and search works - we expect that tempList array will eventually consists of one item { companyName: 'test' }, since our search tag test matches the condition in the filter logic:

  it('should search company', () => {
    component.searchCompany = 'test';
    component.tempList = [];
    component.tempNameList = [
      { companyName: 'abc' },
      { companyName: 'test' },
      { companyName: 'def' },
    ];

    component.search();

    expect(component.tempList).toEqual([{ companyName: 'test' }]);
  });

Upvotes: 3

Related Questions