Search code examples
mockingsinonmockserver

Sinon fakeServer failed to mock POST: 'TypeError: By RFC7230, section 3.2.4, header values should be strings. Got object'


GET method works fine, but always get trouble with POST. my test code is

let server = sinon.createFakeServer();
server.respondImmediately = true;
server.respondWith(`api/v1.0/companies/${companyResponse.id}/orgchart`, [200,  {"Content-Type": "*/*"}, 'OK']);

and below is the ajax call:

  ajax({
    type: "POST",
    url: '/my/api/endpoint',
    data: data,
    processData: false,
    contentType: false,
    complete: this.handleLoadingComplete,
    xhr: function(){
      let xhr = $.ajaxSettings.xhr() ;
      xhr.upload.onprogress = function(evt){
        updateProgress(evt.loaded, evt.total);
      } ;
      xhr.upload.onload = function(){ console.log('loading completed') } ;
      return xhr ;
    }        
  });

using exactly same test code, when I set ajax method to 'GET', it works. But with 'POST' it always failed. This is the response received by complete of the above ajax POST:

`

{ readyState: 0,
      getResponseHeader: [Function: getResponseHeader],
      getAllResponseHeaders: [Function: getAllResponseHeaders],
      setRequestHeader: [Function: setRequestHeader],
      overrideMimeType: [Function: overrideMimeType],
      statusCode: [Function: statusCode],
      abort: [Function: abort],
      state: [Function: state],
      always: [Function: always],
      catch: [Function: catch],
      pipe: [Function: pipe],
      then: [Function: then],
      promise: [Function: promise],
      progress: [Function: add],
      done: [Function: add],
      fail: [Function: add],
      status: 0,
      statusText:
       'TypeError: By RFC7230, section 3.2.4, header values should be strings. Got object' }

` I have no idea what's the error here and I'm stuck for hours.... could anyone kindly help? Will greatly appreciate it!


Solution

  • I have the same issue, and in my case, it is related to how axios is setting headers. It isn't a real solution, but pinning sinon and forcing an older version of nise fixed the problem. Here is a package.json snippet:

      ...
      "devSependencies": {
        ...
        "sinon": "^4.5.0",
        ...
      }
      ...
      "resolutions:" {
        "nise": "1.2.7"
      }
      ...