【问题标题】:React testing library: How to manage the duplicated test codeReact 测试库:如何管理重复的测试代码
【发布时间】:2020-11-20 15:04:59
【问题描述】:

最近我正在使用由不同组件和服务组成的应用程序进行集成测试,因此我正在为与这些元素的不同用户行为交互创建测试。

我注意到我的测试重复了一些常见的初始语句。

例如:

  • 为了显示列表数据,我需要触发一个初始搜索输入。

所以我总是从下一句开始:

beforeEach(() => render(MyComponent))

test('test A', () => {
  fireEvent.click(screen.getByRole('button', {name: /search/i/)))
  // ... rest of the particular test
})

test('test B', () => {
  fireEvent.click(screen.getByRole('button', {name: /search/i/)))
  // ... rest of the particular test
})

test('test C', () => {
  fireEvent.click(screen.getByRole('button', {name: /search/i/)))
  // ... rest of the particular test
})

// and so on...

所以我所做的就是创建一个fireSearchClick 全局函数:

const fireSearchClick = () => fireEvent.click(screen.getByRole('button', {name: /search/i/)))

test('test A', () => {
  fireSearchClick() // <<< now is called in this way
  // ... rest of the particular test
})

我认为这样做的好处是只有一个地方可以更新“火搜索”触发器,例如,如果按钮标签更改为“提交”(就像更改示例一样)。

但是当我继续进行更多测试时,我会以可重复的模式结束,例如:

test('test N', async () => {
  fireSearchClick()

  await loadingData() // another global function that i created for wait results

  fireNextPage() // another global function that i created for go through next page results
  
  await loadingData()

  // the particular things of this test...
})

test('test M', async () => {
  fireSearchClick()

  await loadingData() // another global function that i created for wait results

  fireNextPage() // another global function that i created for go through next page results
  
  await loadingData()

  // the particular things of this test...
})

// and so on...

我关心的是:

  • 这是个好主意吗?
  • 还有其他更好的方法可以在测试中执行可重复的步骤吗?

我正在考虑在 beforeEach 钩子上实现所有初始可重复步骤,但它也许可能包含很多逻辑,当其中一些步骤失败时很难跟踪(例如,如果我在beforeEach 内部执行fireEvent 失败,很难找出错误在哪里)

你怎么看?您如何管理这些场景?

【问题讨论】:

    标签: unit-testing integration-testing react-testing-library


    【解决方案1】:

    您可以将所有设置分组到一个函数中,并在您的测试或 beforeEach 挂钩中调用它

    const setupTest = async () => {
      render(<MyComponent />)
      fireSearchClick()
      await loadingData()
      fireNextPage()
      await loadingData()
    }
    
    test('test M', async () => {
      await setupTest()
      // the particular things of this test...
    })
    

    但是,如果这使测试变得太慢并且您想提高速度,您可以尝试使用已设置的状态渲染特定组件 - 准备好进行测试。即

    render(<MyComponent data={mockData} page={2} />)
    

    【讨论】:

    • 感谢您的回答!我认为这两种选择都是不错的方法,可能第二种方法会更好
    猜你喜欢
    • 1970-01-01
    • 2022-10-20
    • 2021-02-20
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多