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

regexp matchers cannot always be overwritten #603

Open
ryuuji3 opened this issue Mar 8, 2021 · 2 comments
Open

regexp matchers cannot always be overwritten #603

ryuuji3 opened this issue Mar 8, 2021 · 2 comments

Comments

@ryuuji3
Copy link

ryuuji3 commented Mar 8, 2021

Version: latest

Description: when you enable overwriteRoutes, and mock a route twice with a RegExp, it will not mock with the response of the second mock unless you share the same RegExp instance.

Reproduction:

import fetchMock from 'fetch-mock'

fetchMock.config.overwriteRoutes = true

it('foo', () => {
  fetchMock.mock(/example\.com/, 200)

  const successResponse = await fetch('example.com')
  expect(successResponse.status).toBe(200)

  fetchMock.mock(/example\.com/, 404)

  const failureResponse = await fetch('example.com')
  expect(failureResponse.status).toBe(404) // nope, its 200
})

If, however you amend the above to

import fetchMock from 'fetch-mock'

fetchMock.config.overwriteRoutes = true

const exampleMatcher = /example\.com/

it('foo', () => {
  fetchMock.mock(exampleMatcher, 200)

  const successResponse = await fetch('example.com')
  expect(successResponse.status).toBe(200)

  fetchMock.mock(exampleMatcher, 404)

  const failureResponse = await fetch('example.com')
  expect(failureResponse.status).toBe(404) // yep works!
})

it works as expected.

I narrowed this problem down to some code that did a triple equality check but I don't remember where I saw it. That would explain though why a shared reference works, but the earlier one doesn't.

@ryuuji3 ryuuji3 changed the title regexp matchers cannot be overwritten regexp matchers cannot always be overwritten Mar 8, 2021
@wheresrhys
Copy link
Owner

I think this is expected behaviour, though I agree it's not obvious and not documented very well.

To get more transparent behaviour it's best to name your routes

it('foo', () => {
  fetchMock.mock(/example\.com/, 200, {name: 'myroute'})

  const successResponse = await fetch('example.com')
  expect(successResponse.status).toBe(200)

  fetchMock.mock(/example\.com/, 404, , {name: 'myroute'})

  const failureResponse = await fetch('example.com')
  expect(failureResponse.status).toBe(404) // should be 404
})

@ryuuji3
Copy link
Author

ryuuji3 commented Oct 26, 2021

Thank you, naming mocked routes was exactly what we needed to do!

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

2 participants