{"name":"xhr-mock","version":"1.7.0","description":"Utility for mocking XMLHttpRequests in the browser.","keywords":["mock","xhr","test","fake","request","ajax","browser","xmlhttprequest","jquery","superagent"],"repository":{"type":"git","url":"git://github.com/jameslnewell/xhr-mock.git"},"dependencies":{"global":"^4.3.0"},"devDependencies":{"browserify":"^11.0.1","mochify":"^2.13.0","superagent":"^1.3.0"},"scripts":{"test":"mochify","example.build":"mkdir build && browserify -r superagent -r ./index.js:xhr-mock -o build/build.js"},"license":"MIT","gitHead":"afb70f5f58cc8a3063b55220c36f86369bb72714","bugs":{"url":"https://github.com/jameslnewell/xhr-mock/issues"},"homepage":"https://github.com/jameslnewell/xhr-mock#readme","_id":"xhr-mock@1.7.0","_shasum":"c3749f2c68d34ee88af7af5b84ac50764c604351","_from":".","_npmVersion":"3.10.8","_nodeVersion":"6.9.1","_npmUser":{"name":"jameslnewell","email":"james@digitaledgeit.com.au"},"dist":{"shasum":"c3749f2c68d34ee88af7af5b84ac50764c604351","tarball":"http://registry-npm.ywwl.com/xhr-mock/download/xhr-mock-1.7.0.tgz","integrity":"sha512-fKav0Gtj4Zi4K1Uv9Vgta7+kcn0sZgEijcDa0dltlMeP8RcFlGcsK0ZGG0LDNr1hqLWSb4RyOb7q4PYZQw6M+Q==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFi86ma6IIg2izcEwf600zUEyLiJwj7bUhOJ2quCh9OkAiEAmZJpPoVMc7CtpXbHCakXcECqIvEMCXV7TnBUECRzLKs="}],"size":7928,"noattachment":false,"key":"/xhr-mock/-/xhr-mock-1.7.0.tgz"},"maintainers":[{"name":"jameslnewell","email":"james@digitaledgeit.com.au"}],"_npmOperationalInternal":{"host":"packages-12-west.internal.npmjs.com","tmp":"tmp/xhr-mock-1.7.0.tgz_1479767002401_0.410626616794616"},"directories":{},"readme":"# xhr-mock\n\n[![npm (tag)](https://img.shields.io/npm/v/xhr-mock.svg)]()\n[![Build Status](https://travis-ci.org/jameslnewell/xhr-mock.svg?branch=master)](https://travis-ci.org/jameslnewell/xhr-mock)\n[![npm](https://img.shields.io/npm/dm/localeval.svg)]()\n\nUtility for mocking `XMLHttpRequest`.\n\nGreat for testing. Great for prototyping while your backend is still being built.\n\nWorks in NodeJS and in the browser. Is compatible with [Axios](https://www.npmjs.com/package/axios), [jQuery](https://www.npmjs.com/package/jquery), [Superagent](https://www.npmjs.com/package/superagent)\nand probably every other library built on `XMLHttpRequest`. Standard compliant ([http://xhr.spec.whatwg.org/](http://xhr.spec.whatwg.org/)).\n\n###### Documentation\n\n* [Installation](#installation)\n* [Usage](#usage)\n* [API](#api)\n* [How to?](#how-to)\n\n## <a name=\"installation\">Installation</a>\n\n### Using a bundler\n\nIf you are using a bundler like [Webpack](https://www.npmjs.com/package/webpack) or [Browserify](https://www.npmjs.com/package/browserify) then install `xhr-mock` using `yarn` or `npm`:\n\n```bash\nyarn add --dev xhr-mock\n```\n\nNow import `xhr-mock` and start using it in your scripts:\n\n```js\nimport mock from 'xhr-mock';\n```\n\n### Without a bundler\n\nIf you aren't using a bundler like [Webpack](https://www.npmjs.com/package/webpack) or [Browserify](https://www.npmjs.com/package/browserify) then add this script to your HTML:\n\n```html\n<script src=\"https://unpkg.com/xhr-mock/dist/xhr-mock.js\"></script>\n```\n\nNow you can start using the global, `XHRMock`, in your scripts.\n\n## <a name=\"usage\">Usage</a>\n\nFirst off lets write some code that uses `XMLHttpRequest`...\n\n`./createUser.js`\n\n```js\n// we could have just as easily use Axios, jQuery, Superagent\n// or another package here instead of using the native XMLHttpRequest object\n\nexport default function(data) {\n  return new Promise((resolve, reject) => {\n    const xhr = new XMLHttpRequest();\n    xhr.onreadystatechange = () => {\n      if (xhr.readyState == XMLHttpRequest.DONE) {\n        if (xhr.status === 201) {\n          try {\n            resolve(JSON.parse(xhr.responseText).data);\n          } catch (error) {\n            reject(error);\n          }\n        } else if (xhr.status) {\n          try {\n            reject(JSON.parse(xhr.responseText).error);\n          } catch (error) {\n            reject(error);\n          }\n        } else {\n          reject(new Error('An error ocurred whilst sending the request.'));\n        }\n      }\n    };\n    xhr.open('post', '/api/user');\n    xhr.setRequestHeader('Content-Type', 'application/json');\n    xhr.send(JSON.stringify({data: data}));\n  });\n}\n```\n\nNow lets test the code we've written...\n\n`./createUser.test.js`\n\n```js\nimport mock from 'xhr-mock';\nimport createUser from './createUser';\n\ndescribe('createUser()', () => {\n  // replace the real XHR object with the mock XHR object before each test\n  beforeEach(() => mock.setup());\n\n  // put the real XHR object back and clear the mocks after each test\n  afterEach(() => mock.teardown());\n\n  it('should send the data as JSON', async () => {\n    expect.assertions(2);\n\n    mock.post('/api/user', (req, res) => {\n      expect(req.header('Content-Type')).toEqual('application/json');\n      expect(req.body()).toEqual('{\"data\":{\"name\":\"John\"}}');\n      return res.status(201).body('{\"data\":{\"id\":\"abc-123\"}}');\n    });\n\n    await createUser({name: 'John'});\n  });\n\n  it('should resolve with some data when status=201', async () => {\n    expect.assertions(1);\n\n    mock.post('/api/user', {\n      status: 201,\n      reason: 'Created',\n      body: '{\"data\":{\"id\":\"abc-123\"}}'\n    });\n\n    const user = await createUser({name: 'John'});\n\n    expect(user).toEqual({id: 'abc-123'});\n  });\n\n  it('should reject with an error when status=400', async () => {\n    expect.assertions(1);\n\n    mock.post('/api/user', {\n      status: 400,\n      reason: 'Bad request',\n      body: '{\"error\":\"A user named \\\\\"John\\\\\" already exists.\"}'\n    });\n\n    try {\n      const user = await createUser({name: 'John'});\n    } catch (error) {\n      expect(error).toMatch('A user named \"John\" already exists.');\n    }\n  });\n});\n```\n\n## <a name=\"api\">API</a>\n\n### xhr-mock\n\n#### .setup()\n\nReplace the global `XMLHttpRequest` object with the `MockXMLHttpRequest`.\n\n#### .teardown()\n\nRestore the global `XMLHttpRequest` object to its original state.\n\n#### .reset()\n\nForget all the request handlers.\n\n#### .get(url | regex, mock)\n\nRegister a factory function to create mock responses for each GET request to a specific URL.\n\n```js\nmock.get(/\\.*.json$/, {\n  body: JSON.stringify({ data: { id: \"abc\" } })\n});\n```\n\n#### .post(url | regex, mock)\n\nRegister a factory function to create mock responses for each POST request to a specific URL.\n\n#### .put(url | regex, mock)\n\nRegister a factory function to create mock responses for each PUT request to a specific URL.\n\n#### .patch(url | regex, mock)\n\nRegister a factory function to create mock responses for each PATCH request to a specific URL.\n\n#### .delete(url | regex, mock)\n\nRegister a factory function to create mock responses for each DELETE request to a specific URL.\n\n#### .use(method, url | regex, mock)\n\nRegister a factory function to create mock responses for each request to a specific URL.\n\n#### .use(fn)\n\nRegister a factory function to create mock responses for every request.\n\n#### .error(fn)\n\nLog errors thrown by handlers.\n\n### MockXMLHttpRequest\n\n### MockRequest\n\n#### .method() : string\n\nGet the request method.\n\n#### .url() : MockURL\n\nGet the request URL.\n\n#### .header(name : string, value: string)\n\nSet a request header.\n\n#### .header(name : string) : string | null\n\nGet a request header.\n\n#### .headers() : object\n\nGet the request headers.\n\n#### .headers(headers : object)\n\nSet the request headers.\n\n#### .body() : string\n\nGet the request body.\n\n#### .body(body : string)\n\nSet the request body.\n\n### MockResponse\n\n#### .status() : number\n\nGet the response status.\n\n#### .status(code : number)\n\nSet the response status.\n\n#### .reason() : string\n\nGet the response reason.\n\n#### .reason(phrase : string)\n\nSet the response reason.\n\n#### .header(name : string, value: string)\n\nSet a response header.\n\n#### .header(name : string) : string | null\n\nGet a response header.\n\n#### .headers() : object\n\nGet the response headers.\n\n#### .headers(headers : object)\n\nSet the response headers.\n\n#### .body() : string\n\nGet the response body.\n\n#### .body(body : string)\n\nSet the response body.\n\n## <a name=\"how-to\">How to?</a>\n\n### Simulate progress\n\n#### Upload progress\n\nSet the `Content-Length` header and send a body. `xhr-mock` will emit `ProgressEvent`s.\n\n```js\nimport mock from 'xhr-mock';\n\nmock.setup();\n\nmock.post('/', {});\n\nconst xhr = new XMLHttpRequest();\nxhr.upload.onprogress = event => console.log(event.loaded, event.total);\nxhr.open('POST', '/');\nxhr.setRequestHeader('Content-Length', '12');\nxhr.send('Hello World!');\n```\n\n#### Download progress\n\nSet the `Content-Length` header and send a body. `xhr-mock` will emit `ProgressEvent`s.\n\n```js\nimport mock from 'xhr-mock';\n\nmock.setup();\n\nmock.get('/', {\n  headers: {'Content-Length': '12'},\n  body: 'Hello World!'\n});\n\nconst xhr = new XMLHttpRequest();\nxhr.onprogress = event => console.log(event.loaded, event.total);\nxhr.open('GET', '/');\nxhr.send();\n```\n\n### Simulate a timeout\n\nReturn a `Promise` that never resolves or rejects.\n\n```js\nimport mock from 'xhr-mock';\n\nmock.setup();\n\nmock.get('/', () => new Promise(() => {}));\n\nconst xhr = new XMLHttpRequest();\nxhr.timeout = 100;\nxhr.ontimeout = event => console.log('timeout');\nxhr.open('GET', '/');\nxhr.send();\n```\n\n> A number of major libraries don't use the `timeout` event and use `setTimeout()` instead. Therefore, in order to mock timeouts in major libraries, we have to wait for the specified amount of time anyway.\n\n### Simulate an error\n\nReturn a `Promise` that rejects. If you want to test a particular error you an use one of the pre-defined error classes.\n\n```js\nimport mock from 'xhr-mock';\n\nmock.setup();\n\nmock.get('/', () => Promise.reject(new Error()));\n\nconst xhr = new XMLHttpRequest();\nxhr.onerror = event => console.log('error');\nxhr.open('GET', '/');\nxhr.send();\n```\n\n### Proxying requests\n\nIf you want to mock some requests, but not all of them, you can proxy unhandled requests to a real server.\n\n```js\nimport mock, {proxy} from 'xhr-mock';\n\nmock.setup();\n\n// mock specific requests\nmock.post('/', {status: 204});\n\n// proxy unhandled requests to the real servers\nmock.use(proxy);\n\n// this request will receive a mocked response\nconst xhr1 = new XMLHttpRequest();\nxhr1.open('POST', '/');\nxhr1.send();\n\n// this request will receieve the real response\nconst xhr2 = new XMLHttpRequest();\nxhr2.open('GET', 'https://jsonplaceholder.typicode.com/users/1');\nxhr2.send();\n```\n\n### Delaying requests\n\nRequests can be delayed using our handy `delay` utility.\n\n```js\nimport mock, {delay} from 'xhr-mock';\n\nmock.setup();\n\n// delay the request for three seconds\nmock.post('/', delay({status: 201}, 3000));\n```\n\n### Once off requests\n\nRequests can be made on one off occasions using our handy `once` utility.\n\n```js\nimport mock, {once} from 'xhr-mock';\n\nmock.setup();\n\n// the response will only be returned the first time a request is made\nmock.post('/', once({status: 201}));\n```\n\n### send a sequence of responses\n\nIn case you need to return a different response each time a request is made, you may use the `sequence` utility.\n\n```js\nimport mock, {sequence} from 'xhr-mock';\n\nmock.setup();\n\nmock.post('/', sequence([\n  {status: 200}, // the first request will receive a response with status 200\n  {status: 500}  // the second request will receive a response with status 500\n                 // if a third request is made, no response will be sent\n  ]\n));\n```\n\n## License\n\nMIT Licensed. Copyright (c) James Newell 2014.\n","publish_time":1479767002620,"_cnpm_publish_time":1479767002620,"dist-tags":{"latest":"2.5.1","next":"2.0.0-preview.15"}}