在Mocha和Node中如何让Sinon的fakeServer响应jQuery.ajax调用?

时间:2015-10-22 23:20:28

标签: javascript jquery node.js mocha sinon

我在这里看了很多答案,那里的博客帖子,Sinon自己的问题跟踪器中的问题,并没有找到任何确定的东西。到目前为止我大致是:

import XMLHttpRequest from "xhr2";
...
beforeEach((done) => {
  jsdom.env("<!doctype html><html><body><div></div></body></html>", (error, window) => {
    for (var i in require.cache) {delete require.cache[i];}

    Object.assign(global, _.pick(window, "document", "navigator"));
    global.window = window;
    window.console = global.console;
    document.body.dataset = {};

    ...

    global.$ = require("jquery");
    global.$(() => {
      global.$.support.cors = true;
      global.$.ajaxSettings.xhr = () => {return new XMLHttpRequest();};
      const fakeServer = require("sinon/lib/sinon/util/fake_server").fakeServer;
      global.server = fakeServer.create({autoRespond: true});
      done();
    });
  });
});

...

it("should bloody work!", () => {
  server.respondWith([401, {}, ""]);
  ...
  [some test code that triggers an $.ajax call];
});

在$ .ajax错误处理程序中,我将参数记录到$ .ajax失败处理程序并查看:

jqXHR = { readyState: 0,
  getResponseHeader: [Function],
  getAllResponseHeaders: [Function],
  setRequestHeader: [Function],
  overrideMimeType: [Function],
  statusCode: [Function],
  abort: [Function],
  state: [Function],
  always: [Function],
  then: [Function],
  promise: [Function],
  pipe: [Function],
  done: [Function],
  fail: [Function],
  progress: [Function],
  complete: [Function],
  success: [Function],
  error: [Function],
  status: 0,
  statusText: 'Error' }
textStatus = error
errorThrown = [Error]

我是否设置假服务器以响应200和“OK”,或者使用.ajax调用,所有道路都导致状态为0和文本为“错误”。

0 个答案:

没有答案