包详细信息

faux-jax

algolia2kMIT5.0.6

Intercept and respond to requests in the browser (XMLHttpRequest, XDomainRequest) and Node.js (http(s) module)

xhr, XMLHttpRequest, XDomainRequest, ajax

自述文件

faux-jax Version Badge Build Status License Downloads

Browser tests

Intercept and respond to:

npm install faux-jax --save[-dev]

Browser example

var fauxJax = require('faux-jax');

fauxJax.install();

doRequest();
fauxJax.on('request', respond);

// somewhere in your code:
function doRequest() {
  var xhr = new XMLHttpRequest();

  xhr.open('POST', '/dawg');
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.send(
    JSON.stringify({
      YAW: 'dawg'
    })
  );
  xhr.onload = function() {
    console.log(xhr.status); // 200
    console.log(xhr.response); // {zup: 'bro'}
  }
}

// in a test file probably:
function respond(request) {
  request.respond(
    200, { // status
      'Content-Type': 'application/json' // headers
    },
    '{"zup": "bro?"}' //body
  );

  fauxJax.restore();
}

Node.js example

var http = require('http');
var fauxJax = require('faux-jax');

fauxJax.install();

doRequest();
fauxJax.on('request', respond);

function doRequest() {
  http.request('http://www.google.com', function(res) {
    console.log(res.statusCode); // 200

    var chunks = [];
    res.on('data', function(chunk) {
      chunks.push(chunk);
    });

    res.on('end', function() {
      console.log(Buffer.concat(chunks).toString());
    });
  }).end();
}

function respond(request) {
  request.respond(
    200, { // status
      'Content-Type': 'text/plain' // headers
    },
    'Hello Node.js!' //body
  );

  fauxJax.restore();
}

API

fauxJax.install([opts])

Replace global XMLHttpRequest and XDomainRequest with mocks.

  • opts.gzip: boolean. Set to true in nodejs to receive gzipped responses.

fauxJax.on('request', cb)

fauxJax is an EventEmitter.

Everytime a new request is made, you will get a request event.

You can listen to it with cb(request).

All requests have the native properties/methods from the spec.

We also added a couple of handy properties/methods for you to ease testing.

fauxJax.waitFor(nbRequests, cb)

Utility to "wait for n requests". Will call cb(err, requests).

request.requestMethod

request.requestURL

request.requestHeaders

Always {} with XDomainRequest.

request.requestBody

request.respond(status[, headers, body])

request.setResponseHeaders(headers)

request.setResponseBody(body[, cb])

fauxJax.restore()

Sets back global XMLHttpRequest and XDomainRequest to native implementations.

fauxJax.support

Object containing various support flags for your tests, used internally by faux-jax.

Errors

Errors will be emitted when:

  • you try to .install() when already installed
  • you try to .restore() without calling .install()
  • a request was intercepted while no listener set

How

tl;dr; We try to be as close as possible to the mocked native environment.

faux-jax uses feature detection to only expose what's relevant for the current environment.

i.e. on Chrome, we do not intercept nor expose XDomainRequest.

Also if the browser only implement some parts of XMLHttpRequest, we mimic it.

Test

npm test

Develop

npm run dev

Go to http://localhost:8080/__zuul.

Tests are written with tape and run through zuul.

Lint

npm run lint

Uses eslint, see .eslintrc.

Thanks

Inspiration for this module came from:

Many thanks!

Node.js version is using moll/node-mitm.

更新日志

5.0.4 (2016-08-30)

5.0.3 (2016-08-30)

5.0.2 (2016-08-30)

5.0.1 (2016-02-29)

  • fix(listeners): do not leak listeners on response end

5.0.0 (2016-02-20)

  • fix(nodejs): emit end after ending response, not before fixes #11
  • fix(XHR spec): handle sync XHRS
  • fix(XHR spec): new request event is now only on send call, always async if no sync flag

4.2.1 (2015-12-08)

  • fix(0.10): fix gzip option in node 0.10

4.2.0 (2015-12-06)

  • feat(res): provide gzip option in install({gzip:true})

4.1.0 (2015-09-01)

  • fix: iojs fix by upgrading mitm

4.0.0 (2015-05-24)

  • event driven and nodejs support out of beta: it works
  • handle https: protocol in node.js

4.0.0-beta.2 (2015-04-07)

  • keep the event loop alive in Node.js

4.0.0-beta.1 (2015-04-02)

  • BREAKING CHANGE: faux-jax is now asyncrhonous by default, there's no more .requests property on the fauxJax object Now you need to: fauxJax.on('request', function(err, request) {}) This was done while adding the Node.js compatibility and also because asynchronous requests (XHRS, Node.js http) ARE A-S-Y-N-C-H-R-O-N-O-U-S
  • FEATURE: Node.js compatibility, you can now intercept both on the browser and the server

3.0.1 (2015-03-10)

  • upgrade lodash to 3.5.0
  • upgrade writable-window-method to 1.0.3

3.0.0 (2015-03-07)

  • fix getAllResponseHeaders() implementation, returns a string, not an array

2.0.0 (2015-03-06)

  • tune XDomainRequest mock. No eventObject for IE8 in event listeners
  • no eventObject in progress events on all browsers when XDomainRequest

1.7.1 (2015-03-04)

  • throw when calling fauxJax.install() twice

1.7.0 (2015-03-04)

  • do not allow .respond() .setResponseHeaders() .setResponseBody when request timeout or error

1.6.0 (2015-02-26)

  • enhance XDomainRequest implem
  • use writable-window-method

1.5.1 (2015-02-25)

  • no more modifying the environment before any call to fauxJax.install()

1.5.0 (2015-02-25)

  • expose support flags through fauxJax.support

1.4.0 (2015-02-23)

  • do not force a Content-Type if body is null
  • do not force a charset if none set

1.3.0 (2015-02-16)

  • do not duplicate content-type header if case does not matches
  • setRequestHeader() compare header names in a case insensitive
  • setRequestHeader() appends header values

1.2.0 (2015-02-14)

  • better progress events
  • more feature detection, closer to native environment

1.1.0 (2015-02-13)

  • add IE7/8 compatiblity
  • add more feature detection (events, like onload not on IE7)
  • remove IE6 testing, there will be no compatibility
  • do not use deepEqual from tape on IE7/8, fails

1.0.2 (2015-02-12)

  • fix .install() when using XDomainRequest
  • tests ok on IE9
  • ISC => MIT

1.0.1 (2015-02-12)

1.0.0 (2015-02-11)

  • initial