docs/versioned_docs/version-1.x/how-to/mocking-graphql-in-storybook.md
yarn rw storybook.mock.js|ts are automatically imported and become globally scoped, which means that they will be available in all of your stories.Locate the file ending with .mock.js in your Cell's folder. This file exports a value named standard, which is the mock-data that will be returned for your Cell's QUERY.
export const QUERY = gql`
query UserProfileQuery {
userProfile {
id
}
}
`
// UserProfileCell/UserProfileCell.mock.js
export const standard = {
userProfile: {
id: 42
}
}
The value assigned to standard is the mock-data associated to the QUERY, so modifying the QUERY means you need to modify the mock-data.
export const QUERY = gql`
query UserProfileQuery {
userProfile {
id
+ name
}
}
`
// UserProfileCell/UserProfileCell.mock.js
export const standard = {
userProfile: {
id: 42,
+ name: 'peterp',
}
}
Behind the scenes: Redwood uses the value associated to
standardas the second argument tomockGraphQLQuery.
If you want to dynamically modify mock-data based on a queries variables the standard export can also be a function, and the first parameter will be an object containing the variables:
export const standard = (variables) => {
return {
userProfile: {
id: 42,
name: 'peterp',
profileImage: `https://example.com/profile.png?size=${variables.size}`
}
}
}
If you're not using a Cell, or if you want to overwrite a globally scoped mock, you can use mockGraphQLQuery:
export const withReallyLongName = () => {
mockGraphQLQuery('UserProfileQuery', () => {
return {
userProfile: {
id: 99,
name: 'Hubert Blaine Wolfeschlegelsteinhausenbergerdorff Sr.'
}
}
})
return <Header />
}
Use mockGraphQLMutation:
export const standard = /* ... */
mockGraphQLMutation('UpdateUserName', ({ name }) => {
return {
userProfile: {
id: 99,
name,
}
}
})
mockGraphQLQuery and mockGraphQLMutation have access to ctx which allows you to modify the mock-response:
mockGraphQLQuery('UserProfileQuery', (_vars, { ctx }) => {
// Forbidden
ctx.status(403)
})