question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

requestHandler override isn't immediately used in test

See original GitHub issue

Environment

Name Version
msw 0.27.1
node v12.20.1
OS MacOS

Request handlers

// Example of declaration. Provide your code here.
import { setupServer } from 'msw/node'
import { rest } from 'msw'

const server = setupServer(
  graphql.query("Roles", (_req, res, ctx) => res(ctx.data({}))) // return empty object by default
)

server.listen()

Test code

Actual request

// apollo useQuery hook
export const ROLES_QUERY = gql`
    query Roles {
        roles
    }
`
const { data, error } = useQuery(ROLES_QUERY)
console.log('data', data)

test code that fails (using @testing-library/react)

test("some roles query test", () => {
    server.use(
        graphql.query("Roles", (req, res, ctx) =>
            res(
                ctx.data({
                    roles: ["roleA", "roleB"],
                }),
            ),
        ),
    )
  render(<HeaderMenu />)
  // logs data: {}

test code that succeeds

test("some roles query test", async () => {
    server.use(
        graphql.query("Roles", (req, res, ctx) =>
            res(
                ctx.data({
                    roles: ["roleA", "roleB"],
                }),
            ),
        ),
    )
  // only difference here
  const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
  await wait(0)
  // only difference here

  render(<HeaderMenu />)
  // logs data: { roles: ["roleA", "roleB"]}

Current behavior

apollo query returns data: {}

Expected behavior

apollo query to return data: { roles: ["roleA", "roleB"] }

Thoughts + Question

This was a head-scratcher to figure out. Especially as server.printHandlers() run directly after server.use() did always indicate the override as succeeding. Is there a more elegant way to solve this do you think? Or have a better idea of the root cause of why this wait(0) is needed? Has anyone else has run into issues like this?

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:8
  • Comments:15 (7 by maintainers)

github_iconTop GitHub Comments

3reactions
agiveygivescommented, Sep 1, 2021

I could not reproduce the issue with fetch, and I did find an issue on swr that was closed with a resolution on July 22nd. I tested with the resolution in their docs ( https://swr.vercel.app/docs/advanced/cache#reset-cache-between-test-cases ), and did not have any issues after implementing that.

For those that don’t want to click links, add an empty provider to your SWRConfig for tests:

describe('test suite', async () => {
  it('test case', async () => {
    render(
      <SWRConfig value={{ provider: () => new Map() }}>
        <App/>
      </SWRConfig>
    )
  })
})
3reactions
agiveygivescommented, Jun 29, 2021

I was able to reproduce the issue here using swr and msw https://github.com/agiveygives/msw-runtime-handler-issue

It will pass about 50% of the time.

Here are the two api responses and handler lists

using the initially configured handlers

console.log
  undefined

    at App (src/App.tsx:21:11)

console.log
  [rest] GET https://pokeapi.co/api/v2/pokemon
    Declaration: C:\Users\andrewg\Desktop\Projects\msw-cache-issue\src\__mocks__\msw\handlers.ts:7:8

    at node_modules/msw/node/lib/index.js:7780:29
        at Array.forEach (<anonymous>)

console.log
  [rest] GET https://pokeapi.co/api/v2/pokemon/:pokeName
    Declaration: C:\Users\andrewg\Desktop\Projects\msw-cache-issue\src\__mocks__\msw\handlers.ts:13:8

    at node_modules/msw/node/lib/index.js:7780:29
        at Array.forEach (<anonymous>)

console.log
  [rest] GET *
    Declaration: C:\Users\andrewg\Desktop\Projects\msw-cache-issue\src\__mocks__\msw\handlers.ts:19:8

    at node_modules/msw/node/lib/index.js:7780:29
        at Array.forEach (<anonymous>)

console.log
  undefined

    at Object.<anonymous> (src/__tests__/App.test.tsx:20:13)

console.log
  {
    count: 1118,
    next: 'https://pokeapi.co/api/v2/pokemon?offset=10&limit=10',
    previous: null,
    results: [
      { name: 'bulbasaur', url: 'https://pokeapi.co/api/v2/pokemon/1/' },
      { name: 'ivysaur', url: 'https://pokeapi.co/api/v2/pokemon/2/' },
      { name: 'venusaur', url: 'https://pokeapi.co/api/v2/pokemon/3/' },
      { name: 'charmander', url: 'https://pokeapi.co/api/v2/pokemon/4/' },
      { name: 'charmeleon', url: 'https://pokeapi.co/api/v2/pokemon/5/' },
      { name: 'charizard', url: 'https://pokeapi.co/api/v2/pokemon/6/' },
      { name: 'squirtle', url: 'https://pokeapi.co/api/v2/pokemon/7/' },
      { name: 'wartortle', url: 'https://pokeapi.co/api/v2/pokemon/8/' },
      { name: 'blastoise', url: 'https://pokeapi.co/api/v2/pokemon/9/' },
      { name: 'caterpie', url: 'https://pokeapi.co/api/v2/pokemon/10/' }
    ]
  }

    at App (src/App.tsx:21:11)

using the runtime handler

console.log
    undefined

      at App (src/App.tsx:21:11)

  console.log
    [rest] GET https://pokeapi.co/api/v2/pokemon
      Declaration: C:\Users\andrewg\Desktop\Projects\msw-cache-issue\src\__tests__\App.test.tsx:38:12

      at node_modules/msw/node/lib/index.js:7780:29
          at Array.forEach (<anonymous>)

  console.log
    [rest] GET https://pokeapi.co/api/v2/pokemon
      Declaration: C:\Users\andrewg\Desktop\Projects\msw-cache-issue\src\__mocks__\msw\handlers.ts:7:8

      at node_modules/msw/node/lib/index.js:7780:29
          at Array.forEach (<anonymous>)

  console.log
    [rest] GET https://pokeapi.co/api/v2/pokemon/:pokeName
      Declaration: C:\Users\andrewg\Desktop\Projects\msw-cache-issue\src\__mocks__\msw\handlers.ts:13:8

      at node_modules/msw/node/lib/index.js:7780:29
          at Array.forEach (<anonymous>)

  console.log
    [rest] GET *
      Declaration: C:\Users\andrewg\Desktop\Projects\msw-cache-issue\src\__mocks__\msw\handlers.ts:19:8

      at node_modules/msw/node/lib/index.js:7780:29
          at Array.forEach (<anonymous>)

  console.log
    undefined

      at Object.<anonymous> (src/__tests__/App.test.tsx:61:13)

  console.log
    {
      count: 1118,
      next: 'https://pokeapi.co/api/v2/pokemon?offset=10&limit=10',
      previous: null,
      results: [
        { name: 'bulbasaur', url: 'https://pokeapi.co/api/v2/pokemon/1/' },
        { name: 'ivysaur', url: 'https://pokeapi.co/api/v2/pokemon/2/' },
        { name: 'venusaur', url: 'https://pokeapi.co/api/v2/pokemon/3/' },
        { name: 'charmander', url: 'https://pokeapi.co/api/v2/pokemon/4/' },
        { name: 'charmeleon', url: 'https://pokeapi.co/api/v2/pokemon/5/' },
        { name: 'charizard', url: 'https://pokeapi.co/api/v2/pokemon/6/' },
        { name: 'squirtle', url: 'https://pokeapi.co/api/v2/pokemon/7/' },
        { name: 'wartortle', url: 'https://pokeapi.co/api/v2/pokemon/8/' },
        { name: 'blastoise', url: 'https://pokeapi.co/api/v2/pokemon/9/' },
        { name: 'caterpie', url: 'https://pokeapi.co/api/v2/pokemon/10/' }
      ]
    }

      at App (src/App.tsx:21:11)
Read more comments on GitHub >

github_iconTop Results From Across the Web

SolrJ not setting request handler - Stack Overflow
It's true that the visible effect in the "setRequestHandler" method is to just set the qt parameter. But that's not the end of...
Read more >
A Comprehensive Guide to Mock Service Worker (MSW)
Request handler overrides ​​ If you read the MSW documentation carefully, you may be tempted to use the one-time override (res. once()) for...
Read more >
Testing AWS Lambda functions written in Java
public class Handler implements RequestHandler<Map<String,String>, String> { @Override public String handleRequest(Map<String,String> event, ...
Read more >
Testing Your (HTTP) Handlers in Go - questionable services
A typo in your tests can cause unintended behaviour, becasue you're not testing what you think you are. You should also make sure...
Read more >
A testing guide for Express with request and response ...
The approach detailed in this post will be about how to test handlers independently of the Express app instance by calling them directly...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found