繁体   English   中英

使用fakeAsync进行Angular2测试

[英]Angular2 testing with fakeAsync

我正在尝试使用fakeAsync测试Angular 2组件,但是没有设置夹具变量。 实际上,没有调用promise回调。 这是代码:

@Component({
  template: '',
  directives: [GroupBox, GroupBoxHeader]
})
class TestComponent {
  expandedCallback() { this.expandedCalled = true; }
}

it('testing...', inject([TestComponentBuilder], fakeAsync((tcb) => {

  var fixture;

  tcb.createAsync(TestComponent).then((rootFixture) => {
    fixture = rootFixture
  });

  tick();

  fixture.detectChanges();
})));

运行此代码时,我得到:

失败:无法读取未定义类型的属性“ detectChanges”错误:无法读取未定义的属性“ detectChanges”

我不知道为什么不触发回调。 在此存储库中,它可以正常工作: https : //github.com/juliemr/ng2-test-seed/blob/master/src/test/greeting-component_test.ts

有什么线索吗?

注意:我正在使用ES6,Traceur,Angular 2 beta,Karma和Jasmine。

------更新------

它遵循测试失败的存储库:

https://github.com/cangosta/ng2_testing_fakeasync

TestComonentBuilder不适用于templateUrl https://github.com/angular/angular/issues/5662

尝试这种方式https://github.com/antonybudianto/angular2-starter/blob/master/app/simplebind/child.component.spec.ts#L15

关键是要创建一个测试虚拟组件(例如TestComponent ),然后在directives: [...]注册要测试的组件,并使用template: <my-cmp></my-cmp> ,然后传递TestComponenttsb.createAsync(TestComponent)... ,并使用injectAsync

我更喜欢这种方式,因为我可以轻松地模拟来自父级的数据,并向/从组件传递任何输入和处理输出。

 import { it, injectAsync, describe, expect, TestComponentBuilder, ComponentFixture } from 'angular2/testing'; import { Component } from 'angular2/core'; import { ChildComponent } from './child.component'; @Component({ selector: 'test', template: ` <child text="Hello test" [(fromParent)]="testName"></child> `, directives: [ChildComponent] }) class TestComponent { testName: string; constructor() { this.testName = 'From parent'; } } let testFixture: ComponentFixture; let childCompiled; let childCmp: ChildComponent; describe('ChildComponent', () => { it('should print inputs correctly', injectAsync([TestComponentBuilder], (tsb: TestComponentBuilder) => { return tsb.createAsync(TestComponent).then((fixture) => { testFixture = fixture; testFixture.detectChanges(); childCompiled = testFixture.nativeElement; childCmp = testFixture.debugElement.children[0].componentInstance; expect(childCompiled).toBeDefined(); expect(childCmp).toBeDefined(); expect(childCompiled.querySelector('h6')) .toHaveText('From parent'); expect(childCompiled.querySelector('h5')) .toHaveText('Hello test'); }); })); it('should trigger changeMe event correctly', () => { childCmp.changeMe(); testFixture.detectChanges(); expect(childCmp.num).toEqual(1); expect(childCompiled.querySelector('h6')) .toHaveText('Changed from child. Count: ' + childCmp.num); }); }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM