Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GraphQL Default Response Override Test Example #11

Open
orthimnas opened this issue Jun 15, 2020 · 4 comments
Open

GraphQL Default Response Override Test Example #11

orthimnas opened this issue Jun 15, 2020 · 4 comments

Comments

@orthimnas
Copy link

I'd like to see an example test that resets the handlers between tests and configures a unique response per test.

My understanding is that I should be able to add an "override" handler in individual tests that tweak a default configuration.

Here is some pseudo-code that represents what I think is needed for setup / use.

setupTests.js

import { handlers } from './mocks'
const server = setupServer(...handlers)
beforeAll(() => {
  server.listen()
})
afterEach(() => {
  server.resetHandlers()
})
afterAll(() => {
  server.close()
})

Test:

// Appropriate imports here to get access to server
it('Uses default setup', () => {
  // Test here
}

it('Uses custom setup', () => {
  server.use(
    graphql.query('SameQueryAsSetup`, (req, res, ctx) => {
      // Return different response from default
    });
  // Rest of test
}
@kettanaito
Copy link
Member

Hey, @orthimnas! Thanks for asking for this. I'll include a runtime request handler (override) usage scenario in the unit tests as you've suggested.

@orthimnas
Copy link
Author

Appreciate you offering to adding that test - I wasn't able to get it working on a local project and hoped that an example would make it clear what I was missing.

@danielbayerlein
Copy link

danielbayerlein commented Jan 29, 2021

In the meantime, is it possible to override the GraphQL default response?

@kettanaito
Copy link
Member

Hey, @danielbayerlein. It's possible to override GraphQL handlers the same way you override the REST ones.

const server = setupServer(
  graphql.query('GetUser', (req, res, ctx) => {
    return res(ctx.data({ user: { firstName: 'John' } }))
  })
)

afterEach(() => {
  // Don't forget to remove all the handlers added in each individual
  // test via `.use`. 
  server.resetHandlers()
})

test('renders a user', () => {
  server.use(
    // In this particular test the `GetUser` query
    // will resolve to a different user object.
    graphql.query('GetUser', (req, res, ctx) => {
      return res(ctx.data({ user: { firstName: 'Dean' } }))
    })
  )
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants