2016-07-20 90 views
0

我已經爲基於angular-cli的項目創建了一個非常簡單的示例測試。從標題中可以看出,問題在於TestComponentBuilder.createAsync()沒有解決它的承諾。這是我的代碼。我懷疑問題出在karma-test-shim.js配置文件中,但我不確定這一點。儘管我已經爲我的測試設置了「expect(true).toEqual(false)」,但測試的結果總是成功。我與角2-RC4Angular-CLI TestComponentBuilder.createAsync()未解決其承諾

import { 
beforeEach, 
beforeEachProviders, 
describe, 
expect, 
it, 
inject 
} from '@angular/core/testing'; 
import { ComponentFixture, TestComponentBuilder } from '@angular/core/testing'; 

import { Component } from '@angular/core'; 
import { By } from '@angular/platform-browser'; 

describe('Component: CollectionCounterWidgetComponent',() => { 

let builder: TestComponentBuilder; 
beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) { 
builder = tcb; 
})); 

it('should create the CollectionCounterWidgetComponent component', inject([],() => { 
return builder.createAsync(ComponentTestController) 
    .then((fixture: ComponentFixture<any>) => { 
    fixture.detectChanges(); 
    expect(true).toEqual(false); 
    }); 

})); 
}); 

@Component({ 
selector: 'test', 
template: ` 
<h1>why?</h1> 
` 
}) 
class ComponentTestController { 
} 

回答

0

工作在角2 RC4你需要async包裹inject功能的異步測試。這將在AsyncTestZoneSpec中運行您的測試,並確保此區域內的所有異步調用都已完成。

在你的情況,你應該import {async} from '@angular/core/testing'和修改您的測試:

it('should create the CollectionCounterWidgetComponent component', async(inject([],() => { 

    builder.createAsync(TestControllerComponent) 
     .then((fixture: ComponentFixture<any>) => { 
     fixture.detectChanges(); 
     expect(true).toEqual(false); 
     }); 

    })) 
); 

現在如預期測試將會失敗。你也不需要return語句(例如return builder ...)

0

好的邁克爾,你是對的,這是我的錯,但問題仍然存在。我用angular-cli創建了另一個項目,只是爲了讓一個乾淨的項目能夠工作,並且我創建了以下非常簡單的測試。

import { 
async, 
inject, 
describe, 
it, 
expect, 
TestComponentBuilder, 
ComponentFixture 
} from '@angular/core/testing'; 
import { Component } from '@angular/core'; 

import { AppComponent } from './app.component' ; 

describe('Component: AppComponent',() => { 

it('should create an instance', async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { 
    tcb.createAsync(AppComponent) 
    .then(fixture => { 
    expect(true).toBe(false); 
    }) 
}))); 
}); 

但是測試的執行是成功的。我必須提到,默認情況下,angular-cli在當前版本中使用RC3,我已經將角度版本更新爲RC4。我在同一個項目中使用「injectAsync」測試了上述測試,而不是「async(inject ..」)和angular RC3,並且在這種情況下正常工作。謝謝