测试 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);
}
);
}
}