为什么测试失败了

时间:2017-10-23 13:33:17

标签: angular karma-jasmine angular-test angular-unit-test

尝试在此处测试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);
      }
      );
  }

}

1 个答案:

答案 0 :(得分:0)

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

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