Angular2,测试指令,undefined-error

时间:2016-06-23 13:04:25

标签: unit-testing angular jasmine

我试图测试一个名为AceDirective的指令(我使用ace编辑器)。 首先,我构建了一个名为MockSearchDirective的TestComponent,它已经获得了这个指令:

@Component({
    selector: '[testAce]',
    directives: [AceDirective],
    template: '<div ace-editor></div>',
}) class TestAce {}

class MockSearchDirective {
}

现在,如果我的beforeEachbeforeEachProviders获得所需的注射:

beforeEachProviders( () => [
    provide(SearchDirective, {useClass: MockSearchDirective}),
    TestComponentBuilder,
    provide(DataTransportService, {useClass: MockDataTransportService}),
]);

beforeEach( inject( [TestComponentBuilder], (_tcb : TestComponentBuilder) => {
    this.searchDirective = new MockSearchDirective();
    this._dataTransportService = new MockDataTransportService();
    _tcb
       .createAsync(TestAce)
       .then( (fixture : ComponentFixture<TestAce>)=> {
           console.log(fixture);
           this.fixture = fixture;
       });
}));

console.log打印包含Ace-Editor的正确夹具。但是,在具体测试中:

it('Check if editor will be initiated correctly', (done) => {
    console.log(this.fixture);
    // let testAce = this.fixture.componentInstance;
    // let element = this.fixture.nativeElement;//.querySelector('div')
    // let elementRef = this.fixture.elementRef;

    //editor exists
    expect(this.fixture.elementRef).toBeDefined();
    done();
});

失败了。 console.log表示,this.fixtureundefined

我还尝试在测试中注入TextComponentBuilder(而不是通过beforeEach):

it('Check if editor will be initiated correctly', inject( [TestComponentBuilder], (_tcb : TestComponentBuilder) => {
    _tcb
        .createAsync(TestAce)
        .then( (fixture : ComponentFixture<TestAce>)=> {
            console.log(fixture);
            // let testAce = this.fixture.componentInstance;
            // let element = this.fixture.nativeElement;//.querySelector('div')
            // let elementRef = this.fixture.elementRef;

            //editor exists
            expect(fixture.elementRef).toBeDefined();
        });
}));

然后我有一些超时:

  

zone.js:461未处理承诺拒绝:&#39;期待&#39;当没有当前规范时使用,这可能是因为异步测试超时

有谁知道这个错误?以及如何处理它?<​​/ p>

谢谢!

更新

您仍然必须使用return语句,例如:

beforeEach( inject( [TestComponentBuilder], (_tcb : TestComponentBuilder) => {
    this.searchDirective = new MockSearchDirective();
    this._dataTransportService = new MockDataTransportService();
    return _tcb
        .createAsync(TestAce)
        .then( (fixture : ComponentFixture<TestAce>)=> {
            this.fixture = fixture;
        });
}));

0 个答案:

没有答案