Angular2测试 - 未定义注入服务的方法

时间:2016-12-30 12:46:12

标签: angular

我试图测试使用服务的组件(GamePanelComponent): 在GamePanelComponent.ts内:

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);
  });

});

1 个答案:

答案 0 :(得分:3)

您不应该在this回调中使用beforeEach。这不是一个班级。因此,this.playersServiceStub并未指向在playerServiceStub之外声明的相同beforeEach。所以你传递undefined作为提供者。只需使用

playersServiceStub = new PlayersService();