In a spec file, how do I test a component method which has event as its parameter?

Viewed 456

I have an autocomplete menu that I based off of primeng code. The first block of code is what I have in the component file. And the filterBrands(event) is the method I'm trying to test in a separate spec file. The second block is the code in the html file which has the stuff for the actual page. I'm not really sure where to begin in starting to test for this method.

component part:

    brands: string[] = ['Audi','BMW','Fiat','Ford','Honda','Jaguar','Mercedes','Renault','Volvo','VW'];

    filteredBrands: any[];

    brand: string;
    filterBrands(event) {
            this.filteredBrands = [];
            for(let i = 0; i < this.brands.length; i++) {
                let brand = this.brands[i];
                if(brand.toLowerCase().indexOf(event.query.toLowerCase()) == 0) {
                    this.filteredBrands.push(brand);
                }
            }
        }

html part:

<p-autoComplete   header = "Brand Name" placeholder="Search Brand Name" [(ngModel)]="brand" 
     [suggestions]="filteredBrands" (completeMethod)="filterBrands($event)" [minLength] = "1"
     [size] = "37" [dropdown] = "true" (input)  ="dt.filter($event.target.value,'displayName','contains')" (onSelect)="dt.filter(brand,'displayName','contains')">
 </p-autoComplete>
1 Answers

Ok, first thing is that Unit test is all about testing the component by isolating it from other dependencies, as much as possible. So, I would suggest you to test just the behavior of filterBrands function and not worry about @Output of completeMethod of primeng:

it('should have "filterBrands()" pushing data',()=>{
  component.filteredBrands = [];
  const event = {query: "Au"};
  component.filterBrands(event);
  expect(component.filteredBrands.length).toBe(1);
  // and similarly more checks

})

and just on side note, you can have it in more JavaScript way by :

filterBrands(event) {
   this.filteredBrands = this.brands.filter(brand =>               
       brand.toLowerCase().indexOf(event.query.toLowerCase()) == 0
   );
}

Basically, E2E testing should cover how primeng behaves when it is integrated with your component and when some keyboard input is provided to it.

Related