【问题标题】:Angular 2 Http Request to Promise returns zone obj instead of actual dataAngular 2 Http Request to Promise 返回区域 obj 而不是实际数据
【发布时间】:2017-02-02 13:29:09
【问题描述】:

我正在尝试快速测试 ng 2 http 以返回真实数据。我知道有更好/更长的方法来做到这一点。这意味着快速和简单,而不是最佳实践。

我知道服务器会返回数据,因为我可以在另一个终端窗口中看到它。 json 非常简单 {a:b} 因为它只是一个概念证明。

我不在乎它是一个承诺还是一个可观察的,只要它挂在那里返回真实数据——所以我可以弄清楚它确实有效——而不是我想编写生产代码那样。

//app.data.service.ts
import { Injectable }     from '@angular/core';
import { Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';

@Injectable() export class DataService {
    constructor(private http: Http) { 
    }
    public getItems(){
       return this.http.get('http://localhost:8090/data/config.txt')
           .toPromise()
           .then(data => Promise.resolve(data.json()));
    }
}

// app.data.service.spec.ts
/* tslint:disable:no-unused-variable */
import { AppComponent } from './app.component';
import { TestBed, inject, fakeAsync } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { By } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { DataService } from './app.data.service';
describe('DataService', function () {
  let dataService: DataService;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      declarations: [AppComponent],
      providers: [DataService]
    });
    dataService = TestBed.get(DataService);
  });
  it('should be instantiated by the testbed', () => {
    expect(dataService).toBeDefined();
  });
  it('should return get', () => {
    let data = dataService.getItems();
    console.log('test data= ' + data);
    console.log('test string(data)= ' + JSON.stringify(data));
  });
});

//tail end of tests.html
      <tr class="system-out">
        <td colspan="3"><strong>System output:</strong><br />Chrome 53.0.2785 (Mac OS X 10.11.6) LOG: 'WARNING: System.import could not load "systemjs.config.extras.js"; continuing without it.'
<br />Chrome 53.0.2785 (Mac OS X 10.11.6) LOG: Error{originalErr: Error{}}
<br />Chrome 53.0.2785 (Mac OS X 10.11.6) LOG: 'test data= [object Object]'
<br />Chrome 53.0.2785 (Mac OS X 10.11.6) LOG: 'test string(data)= {"__zone_symbol__state":null,"__zone_symbol__value":[]}'
</td>

【问题讨论】:

    标签: javascript angularjs unit-testing http promise


    【解决方案1】:

    在 app.data.service.ts 中

    public getItems(){
       return this.http.get("http://......")
           .toPromise()
           .then(res => res.json())
           .catch(this.handleError);
    }
    

    在你的 component.ts 中调用这个方法/订阅它

      data:any;
    
      ngOnInit() {
        this.appService.getItems()
            .then(data => console.log(data));
    
      }
    

    【讨论】:

      【解决方案2】:

      解决这个问题的几个问题,调试 karma 测试弹出的 chrome 浏览器有帮助 -

      • 服务器未返回 CORS 标头
      • 可观察/订阅代码是 不工作
      • json 数据是 {a:b},当我将其更改为 {"a":"b"} - result.json() 有效

      对于问题 #2,以下是 getItems 的代码:

      //app.data.service.ts
      getItems(url:string) : Observable<Response> {
              return this._http.get(url)
                  .map((response: Response) => {
                      return response;     
                  }).catch(this.handleError);
      };
      
      //app.data.service.spec.ts
      it('should return {a:b}', () => {
      
          let data: string;
      
          dataService.getItems("http://localhost:8090/data/config.json")
                 .subscribe(
                  (response) => {
                      //Here you can map the response to a type
                      console.log("test getItems returned");
                      data = JSON.stringify(response.json());
                      console.log("data = " + data);
                  },
                  (err) => {
                      //Here you can catch the error
                      console.log("test getItems returned err");
                  }
              );
        });
      

      【讨论】:

        猜你喜欢
        • 2021-10-17
        • 2015-05-18
        • 1970-01-01
        • 1970-01-01
        • 2017-03-17
        • 1970-01-01
        • 1970-01-01
        • 2021-03-17
        • 1970-01-01
        相关资源
        最近更新 更多