使用酶和jest

时间:2018-04-09 08:09:05

标签: reactjs async-await jestjs enzyme fetch-mock

我正在使用React <User /> component测试jest enzymefetch-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)
  })
})

1 个答案:

答案 0 :(得分:0)

您试图在两个测试用例中调用 mockUrlWithUser ()(用户,一旦获取了数据就显示数据),这可能会导致此问题。尽量不要两次调用此方法或尝试将2个测试用例变为1。