msw-introspection
Default mocked responses from a graphql query via msw and graphql introspection
createIntrospectionHandler
(introspection) -> (req,res,ctx) -> MockedResponse
Creates a msw handler for GraphQL operations. The handler returns mocked data that conforms to the schema types
Implementation
Setup mocks
import { graphql } from "msw";
import { createIntrospectionHandler } from "msw-introspection";
import introspection from "../../graphql/introspection.json";
const introspectionHandler = createIntrospectionHandler(introspection);
const handlers = [graphql.operation(introspectionHandler)];
export const server = setupServer(...handlers);
Setup Jest
import "@testing-library/jest-dom/extend-expect";
import { client } from "./ApolloClient";
import { server } from "./mocks/server";
beforeAll(() => {
server.listen();
});
beforeEach(() => {
return client.clearStore();
});
afterEach(() => {
server.resetHandlers();
});
afterAll(() => {
server.close();
});
Testing
The testing for this library illustrates how to use MSW to mock a GQL API and get default responses from an introspected schema. The schema used for testing is provided by the SpaceX GraphQL API.
npm run download:schema
The /test
directory sets up an ApolloClient instance, a React component that calls useQuery
, and the utilities that set up the msw server.
├── test
│ ├── graphql
│ │ ├── introspection.json
│ │ ├── schema.gql
│ │ ├── types.d.ts
│ ├── mocks
│ ├── ApolloClient.ts
│ ├── codegen.yml
│ ├── index.test.tsx
│ ├── rockets.tsx
│ ├── setupTests.ts