模拟测试http - angular2

时间:2017-05-09 23:23:38

标签: javascript angular http testing mocking

我在这里阅读了很多问题和一些教程,我仍然无法使其工作,我已经逐字逐句地复制了教程,但仍然没有运气,所以我不知道问题是什么。我对这些东西很新。这是我的代码:

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');
      });
    }));
  });
});

测试失败,预期未定义为3,等等。所以我假设它实际上并没有将我的mockResonse obj作为响应或者那些行上的东西?我猜可能只是一些小事。

服务代码:

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');
  }
}

任何帮助非常感谢。

1 个答案:

答案 0 :(得分:2)

the tutorial that was likely was followed中,服务方法返回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));
  }

因此,回复被模拟为{ data: [...] }

在问题的示例中,它返回this.http.get('/api/items')并且不会调用response.json()

这就是除了断言失败之外没有错误的原因; items必须等于mockReponse

应该是

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

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

这可以另外用

断言
expect(items).toEqual(mockResponse);