fake window.fetch for tests.
$ npm install fake-fetch --save-dev
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();
});
});
Mock window.fetch
before doing anything.
Restore window.fetch
.
Returns request URL.
Returns request method. Default is 'get'.
Returns message body. Default is '' (empty string).
Returns request headers. Default is {} (empty object).
Returns request options. Default is {} (empty object)
Check whether this instance of fakeFetch was ever called
Type: object
The object to be sent as request-body.
Type: object
Custom Response options, see Response
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
MIT © Michał Jezierski