0

测试 http post 服务。但是测试失败并出现以下错误 Expected object to be a kind of Object, but was Response with status: null null for URL: null.

我尝试将 url 添加到 RequestOptions 但它给出了错误。可能是什么问题我似乎无法弄清楚

// 测试文件

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

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


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [
        HttpPostService,
        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 insert new courseList',
    async(inject([HttpPostService], (service: HttpPostService) => {
      mockBackend.connections.subscribe((connection: MockConnection) => {
        expect(connection.request.method).toBe(RequestMethod.Post);
        connection.mockRespond(new Response(new ResponseOptions({})));
        const contentType = connection.request.headers.get('Content-Type');
        expect(contentType).not.toBeNull();
        expect(contentType).toEqual('application/json');
        expect(connection.request.url).toBe('someurl/data.json');
      });
      const courseList: ICourseModel[] = [
        { 'course': 'Mobile Development' },
        { 'course': 'Web Development' },
        { 'course': 'IOS Development' },
        { 'course': 'Android Development' }
      ];
      const result = service.storeData(courseList);
      result.subscribe(
        (successResult) => {
          expect(successResult).toBeDefined();
          expect(successResult).toEqual({});
        });
    })));
});

// http post服务

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { ICourseModel } from '../interface/course-model';
import { Observable } from 'rxjs/Observable';

// HTTP Post service to post the data to the server. Add Content-type in the header while posting a data
@Injectable()
export class HttpPostService {

  constructor(private http: Http) { }

  storeData(crs: ICourseModel[]) {
    const headers = new Headers({'Content-Type': 'application/json'});
    headers.append('Accept', 'application/json');
    return this.http.post('someurl/data.json', crs, {headers: headers}).catch(
      (error: Response) => {
        return Observable.throw(error);
      }
    );
  }
}
4

1 回答 1

0

我认为你把事情复杂化了。不要测试是否http.post有效(角度团队这样做了);测试您的服务是否http.post正确调用。这对您的服务来说应该足够了:

describe('HttpPostService', () => {
  let service: HttpPostService;
  let http;
  const testError = new Error('Test Error');
  const courseList: ICourseModel[] = [
    { 'course': 'Mobile Development' },
    { 'course': 'Web Development' },
    { 'course': 'IOS Development' },
    { 'course': 'Android Development' }
  ];

  beforeEach(() => {
    http = jasmine.createSpyObject('http', ['post']);
    service = new HttpPostService(http);
  });

  it('should work', () => {
    service.storeData(courseList);
    expect(http.post
      .toHaveBeenCalledWith('someurl/data.json', courseList, jasmine.any(Object));
  });

  it('should throw', () => {
    http.post.and.returnValue(Observable.throw(testError));
    // since you're not handling error in HttpPostService, 
    // you don't need to test catch(), 
    // but if there was a HttpPostService.errorHanlder test would be:
    spyOn(service, 'errorHandler');
    service.storeData(courseList);
    expect(service.errorHandler).toHaveBeenCalledWith(testError);
  });
});

您可以了解更多关于茉莉花间谍的信息。

于 2017-10-23T16:17:20.483 回答