【问题标题】:Angular2 - jasmine doesn't recognize object after initializeAngular2 - 茉莉花在初始化后无法识别对象
【发布时间】:2016-12-23 17:54:34
【问题描述】:

我已经创建了这个测试:

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;

我的代码有什么问题?

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    您正在异步创建组件,但您没有等待它准备好,为此,您应该使用异步。

    这是一个更好的例子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      相关资源
      最近更新 更多