我有一个带有简单组件的Angular2应用程序
@Component({
selector: 'Techs',
template: '',
providers: [HTTP_PROVIDERS]
})
export class Techs {
public techs: Tech[];
constructor(http: Http) {
http
.get('src/app/techs/techs.json')
.map(response => response.json())
.subscribe(result => this.techs = result);
}
}
我的测试执行了两次:
Chrome 49.0.2623(Mac OS X 10.11.4):执行0成功6(0秒/ 0秒)
日志:'测试结束'
Chrome 49.0.2623(Mac OS X 10.11.4):成功执行6 6成功(0.182秒/ 0.153秒)
但是,如果我删除了Http调用,则测试只执行一次
Chrome 49.0.2623(Mac OS X 10.11.4):成功执行6 6成功(0.182秒/ 0.153秒)
这是我的测试
describe('techs component', () => {
it('should render 3 elements <tech>', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb
.createAsync(Techs)
.then(fixture => {
fixture.componentInstance.techs = [{}, {}, {}];
fixture.detectChanges();
const techs = fixture.nativeElement;
expect(techs.querySelectorAll('tech').length).toBe(3);
});
}));
});
答案 0 :(得分:0)
我认为您的问题来自HTTP调用的异步方面。我会看到两种解决方法:
MockBackend
类来完成。以下是针对XHRBackend
类配置它:
beforeEachProviders(() => {
return [
HTTP_PROVIDERS,
provide(XHRBackend, { useClass: MockBackend }),
];
});
以及在响应中返回所需内容的方法:
it('Should return a list of dogs', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: [ { name: 'test' }, ... ]
})));
}
(...)