简体   繁体   English

模拟测试http-angular2

[英]mock testing http - angular2

I have read many questions here and a few tutorials and I still can't get this working, I've copied the tutorials word-for-word and still no luck so I have no idea what the issue is. 我在这里阅读了许多问题,并阅读了一些教程,但仍然无法正常工作,我已经逐字逐句地复制了这些教程,但仍然没有运气,所以我不知道问题出在哪里。 I'm pretty new to this stuff. 我对这些东西很陌生。 Here's my code: 这是我的代码:

 import { TestBed, inject, async } from '@angular/core/testing'; import { MockBackend } from '@angular/http/testing'; import { BaseRequestOptions, HttpModule, Http, Response, ResponseOptions } from '@angular/http'; import { ItemsService } from './items.service'; import { MOCKITEMS } from './mock-items'; describe('ItemsService', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpModule], providers: [ItemsService] }); }); it('should construct', inject([ItemsService], (service) => { expect(service).toBeDefined(); })); }); describe('ItemsService Mock', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ ItemsService, MockBackend, BaseRequestOptions, { provide: Http, useFactory: (backend, opts) => new Http(backend, opts), deps: [MockBackend, BaseRequestOptions] } ], imports: [HttpModule] }); }); it('should construct', inject([ItemsService, MockBackend], (service, mockBackend) => { expect(service).toBeDefined(); })); describe('#getItems()', () => { it('should return <Array<Items>>', inject([ItemsService, MockBackend], (service, mockBackend) => { const mockReponse = { data: [ { itemCharId: 1, itemName: 'milk' }, { itemCharId: 2, itemName: 'eggs' }, { itemCharId: 3, itemName: 'meat' } ] } mockBackend.connections.subscribe((connection) => { connection.mockRespond(new Response(new ResponseOptions({ body: JSON.stringify(mockReponse) }))); }); service.getItems().subscribe((items) => { expect(items.length).toBe(3); expect(items[0].itemName).toEqual('milk'); expect(items[1].itemName).toEqual('eggs'); expect(items[2].itemName).toEqual('meat'); }); })); }); }); 

The tests are failing with expected undefined to be 3, etc. So I'm assuming it's not actually getting my mockResonse obj as the response or something on those lines? 测试失败,预期的undefined为3,依此类推。因此,我假设它实际上不是在获取我的mockResonse obj作为响应或类似的东西吗? Could just be something small too I guess. 我猜也可能只是些小东西。

Service code: 服务代码:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ItemsService {

  constructor(private http: Http) { }

  getItems() {
    return this.http.get('/api/items');
  }
}

Any help greatly appreciated. 任何帮助,不胜感激。

In the tutorial that was likely was followed , service method returns response.json().data : 可能遵循的教程中 ,服务方法返回response.json().data

  getHeroes(): Promise<String[]> {
    return this.http.get('myservices.de/api/heroes')
        .toPromise()
        .then(response => response.json().data)
        .catch(e => this.handleError(e));
  }

So the response is mocked as { data: [...] } . 因此,响应被模拟为{ data: [...] }

While in the example in the question it returns this.http.get('/api/items') and doesn't call response.json() . 在问题示例中,它返回this.http.get('/api/items') ,而不调用response.json()

These are the reason why there are no errors except failed assertions; 这就是为什么除了失败的断言之外没有错误的原因。 items has to be equal to mockReponse . items必须等于mockReponse

It should be 它应该是

  getItems() {
    return this.http.get('/api/items').map(res => res.json());
  }

and

  const mockReponse = [
      { itemCharId: 1, itemName: 'milk' },
      { itemCharId: 2, itemName: 'eggs' },
      { itemCharId: 3, itemName: 'meat' }
  ]

This can additionally be asserted with 这可以另外用

expect(items).toEqual(mockResponse);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM