错误:createConnection需要一个Request实例,得到[object Object] - Angular2,SytemJs

时间:2017-01-03 05:18:17

标签: angular karma-runner systemjs

我在使用Angular2,SystemJs尝试使用MockBackends时遇到了问题。我想测试我的服务方法的各种状态,但我不断收到错误(错误:createConnection需要一个Request实例,得到[object Object])。我看不到任何404s'来自Systemjs。我尝试直接从Angular2文档中进行单元测试,因为它不起作用:

我还应该检查什么?

- 我的考试

it('should get a response', () => {
    let connection; //this will be set when a new connection is emitted from the backend.
    let text; //this will be set from mock response
    let injector = ReflectiveInjector.resolveAndCreate([
        MockBackend,
        BaseRequestOptions,
        {provide: Http, useFactory: (backend, options) => {
            return new Http(backend, options);
        }, deps: [MockBackend, BaseRequestOptions]}]);
    let backend = injector.get(MockBackend);
    let http = injector.get(Http);
    backend.connections.subscribe(c => connection = c);
    http.request('https://jsonplaceholder.typicode.com/users').subscribe(res => {
        text = res.text();
    });

    console.log('text: ', text);

    connection.mockRespond(new Response({body: [{'id': 1}]}));

    expect(text).toBeDefined();

});

- 我的服务电话

 return this._http.get(this.url)
            .map(res => res.json());

1 个答案:

答案 0 :(得分:0)

它的

import {ResponseOptions} from '@angular/http'; (...) connection.mockRespond(new Response(new ResponseOptions({body: [{'id': 1}]})));

Response的构造函数期望它的参数在ResponseOptions中包装; - )

P.S。:几天前更新了master分支中的buggy样本,但是doc仍然使用旧标记的样本。新样本已经可以在github上找到:https://github.com/angular/angular/blob/master/modules/@angular/http/testing/mock_backend.ts