2017-01-03 85 views
0

我尝试与Angular2,SystemJs的MockBackends时遇到问题。我想测试我的服务方法的各种状态,但我不断收到错误(错误:createConnection需要一个请求的实例,得到[对象对象])。我无法从Systemjs中看到任何404s。我尝试了直接从Angular2文档中进行单元测试,因为这也不起作用:错误:createConnection需要一个实例的请求,得到[对象对象] - Angular2,SytemJs

我还应该检查什么?

- 我的测试

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()); 

回答

0

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

响应的构造函数需要它的论点ResponseOptions包梁;-)

P.S .:几天前更新了master分支中的越野车示例,但doc仍使用旧标签。新样本可以在github上找到:https://github.com/angular/angular/blob/master/modules/@angular/http/testing/mock_backend.ts

+0

Hi @E。 Hein,我根据你的帖子进行了修改,但我仍然有同样的问题。我只改变了你推荐的行,因为我已经有了ResponseOptions API。任何其他想法我需要看看? – Jimi

+0

早上好吉米,自己试了一下这个例子,它按预期工作:[见connection-response.spec.ts](http://plnkr.co/edit/KWBwBfByHlkFmYlKRcPW?p=preview)。你使用哪个角度版本? (不要以为是因果报应者)PS:显然我们生活在不同的时区^^ –

+0

我使用的是2.3.0,那肯定是问题所在。我已经升级了,似乎有什么问题。我的测试不会因为这个问题而运行,任何有关解决问题的想法?在XMLHttpRequest.ZoneTask.invoke(http:// localhost:9876/base/jspm_packages/npm/zone .js @ 0.7.4/dist/zone.js:293:27)[] 加载http://时出错localhost:9876/base/process.js as“process”from http:// localhost:9 876/base/jspm_packages/npm/@ angular/compiler @ 2.4.1/testing /../ bundles/compiler.umd。 JS' – Jimi

相关问题