This repository illustrates how to use Mock Service Worker to mock a GraphQL API for development, unit and E2E testing in Create React App project.
- Create React App
- Apollo as a GraphQL client;
- Jest for running unit tests;
- React Testing Library for unit test assertions;
- Cypress for running E2E tests;
$ git clone https://github.com/mswjs/examples.git
$ cd examples
$ yarn
$ cd graphql-react-apollo
$ yarn start
$ yarn test:unit
$ yarn test:e2e
src/mocks/handlers.js
describes GraphQL operations to mock.
src/index.js
conditionally enables mocking indevelopment
environment.src/ApolloClient.js
uses an explicitfetch
reference in order for requests to be captured and deferred until the Service Worker is ready. Necessary due to Apollo hoisting a nativewindow.fetch
call, preventing Mock Service Worker from properly capturing it.public/mockServiceWorker.js
the Service Worker, created by runningnpx msw init public
.
src/setupTests.js
enables mocking for unit tests viabeforeAll
/afterAll
hooks.