0

我正在测试一个React <User /> componentwithjestenzymeusing fetch-mock。但是当我尝试运行两个测试时,<User />我得到了这个错误。

 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.

这是我的测试:

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)
  })
})

4

1 回答 1

0

您正在尝试在两个测试用例(用户,在获取数据后显示数据)中调用mockUrlWithUser (),这可能会导致您出现此问题。尽量不要调用这个方法两次或者尽量把2个测试用例变成1个。

于 2018-04-11T09:20:36.557 回答