fake window.fetch for tests
JavaScript
Switch branches/tags
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.editorconfig eslint Apr 12, 2018
.eslintrc eslint Apr 12, 2018
.gitignore fake-fetch Jun 10, 2015
.travis.yml
README.md Update dependencies, add new methods Apr 12, 2018
index.js
karma.conf.js
package.json
test.js eslint Apr 12, 2018

README.md

fake-fetch Build Status

fake window.fetch for tests.

Installation

$ npm install fake-fetch --save-dev

Usage

var fakeFetch = require('fake-fetch');

beforeEach(fakeFetch.install);
afterEach(fakeFetch.restore);

it("should fetch what you need", done => {
  fakeFetch.respondWith({"foo": "bar"});

  fetch('/my-service', {headers: new Headers({accept: 'application/json'})}).then(data => {
    expect(fakeFetch.getUrl()).toEqual('/my-service');
    expect(fakeFetch.getMethod()).toEqual('get');
    expect(data._bodyText).toEqual('{"foo":"bar"}');
    expect(fakeFetch.getRequestHeaders()).toEqual(new Headers({accept: 'application/json'}));
    done();
  });
});

API

install

Mock window.fetch before doing anything.

restore

Restore window.fetch.

getUrl

Returns request URL.

getMethod

Returns request method. Default is 'get'.

getBody

Returns message body. Default is '' (empty string).

getRequestHeaders

Returns request headers. Default is {} (empty object).

getOptions

Returns request options. Default is {} (empty object)

respondWith(data, options)

data

Type: object

The object to be sent as request-body.

options

Type: object

Custom Response options, see Response

Remarks

You may find necessary to use browserify before using fake-fetch within your specs, e.g.

// karma.conf.js
preprocessors: {
  './node_modules/fake-fetch/index.js': [ 'browserify' ]
}

Real-life usage example can be found here https://github.com/msn0/file-downloader/blob/master/test.js

License

MIT © Michał Jezierski