响应状态:对于URL为null null:测试http post服务时为null erorr

时间:2017-10-23 15:38:08

标签: angular karma-jasmine angular-test

测试http post serivce。但测试失败,出现以下错误 预期对象是一种Object,但是响应状态:对于URL为null null。

我尝试将网址添加到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 service

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

}

1 个答案:

答案 0 :(得分:0)

我认为你过分复杂了。不要测试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); }); }); 是否有效(有角度的团队那样做);测试您的服务是否正确调用progressBar1.addChangeListener(e -> { javax.swing.JProgressBar bar = (javax.swing.JProgressBar)e.getSource(); if(bar.getValue() == 100) text2.setText("You dit it"); }); 。这应该足以满足您的服务:

multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  library(grid)

  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)

  numPlots = length(plots)

  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                    ncol = cols, nrow = ceiling(numPlots/cols))
  }

 if (numPlots==1) {
    print(plots[[1]])

  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))

      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}

您可以找到有关jasmine spies的更多信息。