use-mock-service-worker
-
Don't mock fetch or axios.
-
use-mock-service-worker is a testing hook which consumes Mock Service Worker API and takes care of all the configuration we have to do while testing ajax calls via mocking the service worker.
-
use-mock-service-worker only plays along with GET requests, one at a time.
-
Whenever we make a http request, use-mock-service-worker intercepts that request before it goes out to internet and then responds with whatever our API's expected response is. This way we can test Ajax calls without making an external http request.
Installation
yarn add -D use-mock-service-worker
or
npm i -D use-mock-service-worker
Usage
// index.test.js // our actual Ajax call method // target APIconst url = 'https://jsonplaceholder.typicode.com/posts'; // expected response from the APIconst dataExpected = "userId": 1 "id": 1 "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit" "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" ; // loadTestServer returns the server created my msw (mock service worker)const server = ; // making sure our server starts before out tests and closes after them too;;; ;