0

尝试在此处测试 http get 服务但测试失败。为什么它不起作用。我已经提供了所有依赖项和所有内容,但它仍然给出未定义的响应

当我运行业力测试运行器时,测试未能给出以下错误

HttpGetService should get courseList Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL

HttpGetService should get courseList async Expected undefined to be 4

// Http 获取服务规范测试文件

import { async, ComponentFixture, TestBed, getTestBed, inject } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { HttpGetService } from './http-get.service';
import {
  BaseRequestOptions, Http, XHRBackend, HttpModule,
  Response, ResponseOptions, RequestMethod
} from '@angular/http';
import {ICourseModel} from '../interface/course-model';

describe('HttpGetService', () => {
  let mockBackend: MockBackend;


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [
        HttpGetService,
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          deps: [MockBackend, BaseRequestOptions],
          useFactory:
          (backend: XHRBackend, defaultOptions: BaseRequestOptions) => {
            return new Http(backend, defaultOptions);
          }
        }
      ],
      imports: [
        HttpModule
      ]
    });
    mockBackend = getTestBed().get(MockBackend);
  }));


  it('should get courseList', (done) => {
    let getDataService: HttpGetService;

    getTestBed().compileComponents().then(() => {
      mockBackend.connections.subscribe(
        (connection: MockConnection) => {
          connection.mockRespond(new Response(
            new ResponseOptions({
              body:  [
                { 'course': 'Mobile Development' },
                { 'course': 'Web Development' },
                { 'course': 'IOS Development' },
                { 'course': 'Android Development' }
              ]
            }
            )));
        });

      getDataService = getTestBed().get(getDataService);
      expect(getDataService).toBeDefined();

      getDataService.getData().subscribe((CourseList: ICourseModel[]) => {
        expect(CourseList.length).toBeDefined();
        expect(CourseList.length).toEqual(4);
        expect(CourseList.length).not.toBe(1);
        done();
      });
    });
  });


  it('should check the service',
    inject([HttpGetService], (service: HttpGetService) => {
      expect(service).toBeTruthy();
    }));

  it('should get courseList async',
    async(inject([HttpGetService], (getDataService: HttpGetService) => {
      mockBackend.connections.subscribe(
        (connection: MockConnection) => {
          connection.mockRespond(new Response(
            new ResponseOptions({
              body:  [
                { 'course': 'Mobile Development' },
                { 'course': 'Web Development' },
                { 'course': 'IOS Development' },
                { 'course': 'Android Development' }
              ]
            }
            )));
        });
      getDataService.getData().subscribe(
        (response) => {
          expect(response.length).toBe(4);
          expect(response[0].course).toBe('Mobile Development');
          expect(response[1].course).toBe('Web Development');
          expect(response).toEqual([
            { 'course': 'Mobile Development' },
            { 'course': 'Web Development' },
            { 'course': 'IOS Development' },
            { 'course': 'Android Development' }
          ]);
        });
    })));
});

// Http服务

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

@Injectable()
export class HttpGetService {

  constructor(private http: Http) { }

  getData() {
    return this.http.get('someurl/data.json').map(
      (response) => {
        const data = response.json();
        const keys = Object.keys(data);
        return data[keys[0]];
      }
    ).catch(
      (error: Response) => {
        return Observable.throw(error);
      }
      );
  }

}
4

1 回答 1

0

如果可以,请使用较新的 HttpClient 并查看此网站,它帮助我解决了类似的问题:

https://chariotsolutions.com/blog/post/new-httpclient-angular-4-3-x-drys-network-calls-testing/

于 2017-11-02T16:05:44.860 回答