storybook/docs/snippets/react/msw-addon-configure-handlers-graphql.ts.mdx
Kyle Gach 01c65098a8 Address feedback
- Re-order TOC items
- Fix conditional content
- Improve nextjs module API references
- Make example snippets more consistent
- Re-organize subpath imports section of module mocking guide
- Fix typos, grammar
2024-04-30 13:54:10 -06:00

100 lines
2.0 KiB
Plaintext

```ts
// YourPage.stories.ts|tsx
import type { Meta, StoryObj } from '@storybook/react';
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';
import { graphql, HttpResponse, delay } from 'msw';
import { DocumentScreen } from './YourPage';
const mockedClient = new ApolloClient({
uri: 'https://your-graphql-endpoint',
cache: new InMemoryCache(),
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
},
});
//👇The mocked data that will be used in the story
const TestData = {
user: {
userID: 1,
name: 'Someone',
},
document: {
id: 1,
userID: 1,
title: 'Something',
brief: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
status: 'approved',
},
subdocuments: [
{
id: 1,
userID: 1,
title: 'Something',
content:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
status: 'approved',
},
],
};
const meta: Meta<typeof DocumentScreen> = {
component: DocumentScreen,
decorators: [
(Story) => (
<ApolloProvider client={mockedClient}>
<Story />
</ApolloProvider>
),
],
};
export default meta;
type Story = StoryObj<typeof SampleComponent>;
export const MockedSuccess: Story = {
parameters: {
msw: {
handlers: [
graphql.query('AllInfoQuery', () => {
return new HttpResponse.json({
data: {
AllInfo: {
...TestData,
},
}
});
}),
],
},
},
};
export const MockedError: Story = {
parameters: {
msw: {
handlers: [
graphql.query('AllInfoQuery', async () => {
await delay(800);
return new HttpResponse.json({
errors: [
{
message: 'Access denied',
},
],
});
}),
],
},
},
};
```