簡體   English   中英

Angular2測試

[英]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();現在它已經崩潰了this.loadingBar.start(); getListing函數中。

只需模擬所有服務並通過使用expect(mockService.someMethod).toHaveBeenCalled()檢查組件是否構成正確的服務類來測試其行為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調用,我將其抽象為服務,以便您可以模擬該服務。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM