2016-12-23 70 views
0

我創造了這個測試之後茉莉花不能識別對象:Angular2 - 初始化

import { ComponentFixture, TestBed } from '@angular/core/testing'; 
import { By }    from '@angular/platform-browser'; 
import { DebugElement } from '@angular/core'; 

import { GamePanelComponent } from './gamepanel.component'; 

describe('GamePanelComponent (inline template)',() => { 

    let comp: GamePanelComponent; 
    let fixture: ComponentFixture<GamePanelComponent>; 

    beforeEach(() => { 

    TestBed.configureTestingModule({ 
     declarations: [ GamePanelComponent ], // declare the test component 
    }).compileComponents() 
     .then(() => { 
      fixture = TestBed.createComponent(GamePanelComponent);    
      comp = fixture.componentInstance; 
     }); 
    }); 

    it('isValidMove',() => {  
     comp.ngOnInit(); 
     comp.game.board[0][0] = 'X'; 
     let isValid = comp.isValidMove(0,0); 
     expect(isValid).toBe(false); 
    }); 

}); 

奇怪的是,測試失敗,因爲TypeError: Cannot read property 'ngOnInit' of undefined錯誤。

顯然,comp乃至fixture未定義。正如你可以看到我做的beforeEach方法對它們進行初始化:

是什麼在我的代碼的問題?

回答

0

您正在異步創建組件,但您並未等待它已準備就緒,爲此,應使用異步。

這裏是一個更好的例子:

let comp; 
let fixture; 
beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     imports : [ ], 
     declarations : [ 
      GamePanelComponent 
     ], 
     providers : [ 
     ] 
    }); 
    TestBed.compileComponents(); 

    fixture=TestBed.createComponent(TestComponent); 
    comp = fixture.componentInstance; 
     fixture.detectChanges(); 

    })); 

it('should create my component ',() => { 

     expect(comp.ngOnInit).toBeDefined() 

});