简体   繁体   中英

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? 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 :

  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: [...] } .

While in the example in the question it returns this.http.get('/api/items') and doesn't call response.json() .

These are the reason why there are no errors except failed assertions; items has to be equal to 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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