使用fakeAsync进行Angular2测试

时间:2016-01-12 10:55:53

标签: unit-testing angular karma-jasmine

我试图使用fakeAsync来测试Angular 2组件,但是没有设置fixture变量。事实上,没有调用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'未定义的           TypeError:无法读取属性' 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

2 个答案:

答案 0 :(得分:2)

TestComonentBuilder无法使用templateUrl https://github.com/angular/angular/issues/5662

答案 1 :(得分:2)

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

重点是创建一个测试虚拟组件(例如TestComponent)并在directives: [...]中注册要测试的组件并使用template: <my-cmp></my-cmp>,然后传递TestComponent } tsb.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);
    });
});