0

I have am testing a React <User /> component with jest and enzyme using fetch-mock. But when I try to run two tests for the <User /> I get this error.

 FAIL  ./user.test.js
User
✓ it shows the loading text before the data is fetched (2ms)
✕ shows the data once it has been fetched (1ms)

● User › shows the data once it has been fetched

Adding route with same name as existing route. See `overwriteRoutes` option.

  at Object.<anonymous>.FetchMock.addRoute (node_modules/fetch-mock/src/lib/set-up-and-tear-down.js:47:9)
  at mockUrlWithUser (user.test.js:21:25)
  at _callee3$ (user.test.js:36:13)
  at step (user.test.js:4:370)
  at user.test.js:4:600
      at new Promise (<anonymous>)
  at Object.<anonymous> (user.test.js:4:281)
      at new Promise (<anonymous>)
      at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:160:7)

  Test Suites: 1 failed, 1 total
  Tests:       1 failed, 1 passed, 2 total
  Snapshots:   0 total
  Time:        0.284s, estimated 1s
  Ran all test suites related to changed files.

Here is what my test is:

import React from 'react'
import { shallow } from 'enzyme'
import User from './user'
import fetchMock from 'fetch-mock'

const nextTick = async () => {
  return new Promise(resolve => {
    setTimeout(resolve, 0)
  })
}

const dummyUser = {
  id: 1,
  name: 'Jack Franklin',
  website: 'https://javascriptplayground.com',
}

const url = 'https://jsonplaceholder.typicode.com/users/1'

const mockUrlWithUser = user =>
  fetchMock.getOnce(url, {
    status: 200,
    body: user,
  })

describe('User', () => {
  
  it('it shows the loading text before the data is fetched', async () => {
    mockUrlWithUser(dummyUser)

    const wrapper = shallow(<User id={1} />)
    expect(wrapper.find('p').text()).toEqual('Loading!')
  })

  it('shows the data once it has been fetched', async () => {
    mockUrlWithUser(dummyUser)

    const wrapper = shallow(<User id={1} />)

    await nextTick()
    wrapper.update()

    expect(wrapper.find('h4').text()).toEqual(dummyUser.name)
    expect(wrapper.find('p').text()).toContain(dummyUser.website)
  })
})
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Amen Ra
  • 2,843
  • 8
  • 47
  • 85
  • Does this help you: https://stackoverflow.com/questions/49031208/how-to-mock-several-gets-in-fetch-mock ? – Moyote Apr 09 '18 at 16:24

1 Answers1

0

You are trying to call mockUrlWithUser() in both the test cases (User,shows the data once it has been fetched) which might be causing this issue for you. Try not to call this method twice or try to make the 2 test cases into 1.

Roopak Puthenveettil
  • 1,387
  • 2
  • 13
  • 27