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:e2esrc/mocks/handlers.jsdescribes GraphQL operations to mock.
src/index.jsconditionally enables mocking indevelopmentenvironment.src/ApolloClient.jsuses an explicitfetchreference in order for requests to be captured and deferred until the Service Worker is ready. Necessary due to Apollo hoisting a nativewindow.fetchcall, preventing Mock Service Worker from properly capturing it.public/mockServiceWorker.jsthe Service Worker, created by runningnpx msw init public.
src/setupTests.jsenables mocking for unit tests viabeforeAll/afterAllhooks.