home.component.spec.ts 2.26 KB
Newer Older
Exbrayat Cédric's avatar
Exbrayat Cédric committed
1
2
3
4
5
6
7
import { TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';
import { ComponentTester, speculoosMatchers } from 'ngx-speculoos';

import { HomeComponent } from './home.component';
8
9
10
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap';
import { SearchService } from '../search.service';
Exbrayat Cédric's avatar
Exbrayat Cédric committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

class HomeComponentTester extends ComponentTester<HomeComponent> {
  constructor() {
    super(HomeComponent);
  }

  get searchBar() {
    return this.input('input');
  }

  get searchButton() {
    return this.button('button');
  }
}

describe('HomeComponent', () => {
  beforeEach(() => TestBed.configureTestingModule({
28
    imports: [ReactiveFormsModule, RouterTestingModule, HttpClientTestingModule, NgbTypeaheadModule.forRoot()],
Exbrayat Cédric's avatar
Exbrayat Cédric committed
29
30
31
32
33
34
35
36
37
    declarations: [HomeComponent]
  }));

  beforeEach(() => jasmine.addMatchers(speculoosMatchers));

  it('should navigate to search when a query is entered', () => {
    // given a component
    const router = TestBed.get(Router) as Router;
    spyOn(router, 'navigate');
38
39
40
41

    const searchService = TestBed.get(SearchService) as SearchService;

    const component = new HomeComponent(router, searchService);
Exbrayat Cédric's avatar
Exbrayat Cédric committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

    // with a query
    const query = 'Bacteria';
    component.searchForm.get('search').setValue(query);
    // when searching
    component.search();

    // then it should redirect to the search with correct parameters
    expect(router.navigate).toHaveBeenCalledWith(['/search'], { queryParams: { query } });
  });

  it('should display a search bar and trigger a search', () => {
    // given a component
    const tester = new HomeComponentTester();
    const component = tester.componentInstance;
    spyOn(component, 'search');

    // then it should display the search bar containing that query
    tester.detectChanges();

    expect(tester.searchBar).toHaveValue('');

    // with a query
    const query = 'Bacteria';
    tester.searchBar.fillWith(query);

    // trigger search
    tester.searchButton.click();
    expect(component.search).toHaveBeenCalled();
    expect(component.searchForm.get('search').value).toBe(query);
  });
});