2017-02-07 3 views
0

Закреплено о том, как протестировать компонент, который имеет много зависимостей третьих лиц. Довольно уверен, что я приближаюсь к этому неправильно, я не знаю, с чего начать. Вот компонент:Angular2 Testing

import { Component, OnInit } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 

import { GameService } from '../game.service'; 
import { environment } from '../../../environments/environment'; 

import { ActivatedRoute } from '@angular/router'; 
import { SlimLoadingBarService } from 'ng2-slim-loading-bar'; 

@Component({ 
    selector: 'app-list', 
    templateUrl: 'list.component.html', 
    styleUrls: ['list.component.scss'] 
}) 

export class ListComponent implements OnInit { 
    config = environment.config; 
    games; 
    headers; 
    params = { 
    searchTerm: '', 
    searchOwner: '', 
    searchType: '', 
    order: 'name', 
    orderType: 'DESC', 
    currentPage: 1, 
    page: 1 
    }; 
    pages; 
    totalRecords; 
    recordsPerPage = 25; 
    exportUrl; 
    personasPage = 1; 
    searchUrl = environment.config.apiUrl + 'personas/'; 
    public buffer: any; 
    public personas: any; 
    buttonSpinner: string = 'none'; 

    constructor(
    private gameService: GameService, 
    private http: Http, 
    private route: ActivatedRoute, 
    private loadingBar: SlimLoadingBarService 
) { } 

    ngOnInit() { 
    this.getListing(); 
    this.getPersonas(); 
    } 

    sort(e, order) { 
    e.preventDefault(); 
    this.params.orderType = (order === this.params.order && this.params.orderType === 'DESC') ? 'ASC' : 'DESC'; 
    this.params.order = order; 
    this.params.page = this.params.currentPage = 1; 
    this.getListing(); 
    } 

    updateListing(page) { 
    this.params.page = this.params.currentPage = page; 
    this.getListing(); 
    } 

    getListing() { 
    this.loadingBar.start(); 
    this.gameService.getGames(this.params) 
     .subscribe((res) => { 
     this.loadingBar.complete(); 
     this.buttonSpinner = 'none'; 

     this.games = res.json(); 
     this.headers = res.headers; 

     this.totalRecords = this.headers.get('x-total'); 
     this.recordsPerPage = this.headers.get('x-limit'); 

     this.exportUrl = this.gameService.getExportLink(this.params); 
     }); 
    } 

    getPersonas() { 
    this.http.get(this.searchUrl + '?page=' + this.personasPage) 
    .map((res: Response) => res.json()) 
    .subscribe((d: {}) => { 
     this.buffer = d; 
     if (this.personas === undefined) { 
     this.personas = this.buffer; 
     // console.log(this.personas); 
     this.personasPage += 1; 
     this.getPersonas(); 
     } else { 
     for (let key in this.buffer) { 
      this.personas.push(this.buffer[key]); 
     } 
     this.personasPage += 1; 
     if (this.buffer.length === 25) { 
      this.getPersonas(); 
     } 
     } 
    }); 
    } 

    onSubmitSearch() { 
    this.buttonSpinner = 'searching'; 
    this.params.page = this.params.currentPage = 1; 
    this.getListing(); 
    } 

    clearSearch(e) { 
    e.preventDefault(); 
    this.buttonSpinner = 'clearing'; 
    this.params.searchTerm = ''; 
    this.params.searchType = ''; 
    this.params.searchOwner = ''; 
    this.params.page = this.params.currentPage = 1; 
    this.getListing(); 
    } 
} 

Вот тест я попытался написания:

import { TestBed, async, ComponentFixture } from '@angular/core/testing'; 
import {} from 'jasmine'; 
import { Http } from '@angular/http'; 
import { ActivatedRoute, RouterModule } from '@angular/router'; 
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; 
import { FormsModule } from '@angular/forms'; 

import { ListComponent } from './list.component'; 
import { GameService } from '../game.service'; 
import { PageitComponent } from '../../shared/pageit/pageit.component'; 

import { SlimLoadingBarService } from 'ng2-slim-loading-bar'; 
import { LaddaModule } from 'angular2-ladda'; 

describe('ListComponent',() => { 
    let gameService, http, route, loadingBar; 
    let component: ListComponent; 
    let fixture: ComponentFixture<ListComponent>; 

    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ ListComponent, PageitComponent ], 
     providers: [ 
     { provide: GameService, useValue: gameService }, { provide: Http, useValue: http }, { provide: ActivatedRoute, useValue: route }, 
     { provide: SlimLoadingBarService, useValue: loadingBar } 
     ], 
     imports: [FormsModule, LaddaModule, RouterModule] 
    }).compileComponents(); 
    }); 

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

    it('should create an instance of the component',() => { 
    component.ngOnInit(); 
    expect(component).toBeDefined(); 
    }); 
}); 

До сих пор я получил это признать первонач, теперь это нарушение из-за this.loadingBar.start(); внутри функции getListing ,

ответ

0

Просто высмеивать все службы и проверять поведение компонента, проверяя, что он делает правильный класс обслуживания, используя expect(mockService.someMethod).toHaveBeenCalled().

Например

let loadingBar: SlimLoadingBarService; 
let gameService: GameService; 

beforeEach(() => { 
    loadingBar = { 
    start: jasmine.createSpy('start'), 
    complete: jasmine.createSpy('complete') 
    }; 
    gameService = { 
    getGames: (params) => Observable.of(whatever) 
    }; 

    TestBed.configureTestingModule({ 
    providers: [ 
     { provide: SlimLoadingBarService, useValue: loadingBar }, 
     { provide: GameService, useValue: gameService } 
    ] 
    }) 
}) 

it('..',() -> { 
    component.getListing(); 

    expect(loadingBar.start).toHaveBeenCalled(); 

    // component calls gameService.getGames is called, wait for async 
    // to finish by called fixture.whenStable 

    fixture.whenStable().then(() => { 
    expect(loadingBar.complete).toHaveBeedCalled(); 
    }) 
}) 

Для вас Http вызова в компоненте, я бы абстрактным, что в сервис, так что вы можете издеваться эту услугу.

 Смежные вопросы

  • Нет связанных вопросов^_^