我创建了这个测试:
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
方法初始化它们:
fixture = TestBed.createComponent(GamePanelComponent);
comp = fixture.componentInstance;
我的代码中出现了什么问题?
答案 0 :(得分: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()
} );