首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用酶和jest运行两个fetch模拟测试时出错。

使用酶和jest运行两个fetch模拟测试时出错。
EN

Stack Overflow用户
提问于 2018-04-09 08:09:04
回答 1查看 951关注 0票数 0

我正在用jest测试React <User /> component,用fetch-mock测试enzyme。但是,当我试图为<User />运行两个测试时,我会得到这个错误。

代码语言:javascript
复制
 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.

下面是我的测试:

代码语言:javascript
复制
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)
  })
})

EN

回答 1

Stack Overflow用户

发布于 2018-04-11 09:20:36

在这两个测试用例中,您都试图调用mockUrlWithUser() (用户,在数据被获取后显示数据),这可能会导致这个问题。尽量不要调用此方法两次,或者尝试将两个测试用例转换为1。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49728223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档