1
我試圖測試其使用的服務的組件(GamePanelComponent
): 內GamePanelComponent.ts
:Angular2測試 - 注入服務的方法是沒有定義
constructor(private playerService: PlayersService, private leaderBoardService: LeaderBoardService) { }
comp.IsValidMove
是利用玩家服務getPlayers
方法,但不幸的是我得到這個錯誤:TypeError: Cannot read property 'getPlayers' of undefined
這是我的測試文件,它是根據Angular2測試教程編寫的。你可以,看我注入其中有getPlayers()
方法的存根(因爲它是原服務的實例):
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { GamePanelComponent } from './gamepanel.component';
import { GamePanelOutputComponent } from '../gamepaneloutput/gamepaneloutput.component';
import { PlayersService } from '../../services/players/players.service';
import { LeaderBoardService } from '../../services/leaderboard/leaderboard.service';
import { Player } from '../../models/player/player';
describe('GamePanelComponent (inline template)',() => {
let comp: GamePanelComponent;
let fixture: ComponentFixture<GamePanelComponent>;
let playersService, playersServiceStub, componentPlayersService : PlayersService;
beforeEach(async (() => {
this.playersServiceStub = new PlayersService();
this.playersServiceStub.players = [];
this.playersServiceStub.players[0] = new Player('','X');
this.playersServiceStub.players[1] = new Player('','O');
TestBed.configureTestingModule({
declarations: [ GamePanelComponent, GamePanelOutputComponent ], // declare the test component
providers: [ { provide: PlayersService, useValue: playersServiceStub }, { provide: LeaderBoardService } ]
}).compileComponents()
.then(() => {
fixture = TestBed.createComponent(GamePanelComponent);
comp = fixture.componentInstance;
// PlayerService actually injected into the component
playersService = fixture.debugElement.injector.get(PlayersService);
componentPlayersService = playersService;
// PlayersService from the root injector
playersService = TestBed.get(PlayersService);
});
}));
it('isValidMove',() => {
comp.ngOnInit();
comp.game.board[0][0] = 'X';
let isValid = comp.isValidMove(0,0);
expect(isValid).toBe(false);
});
});