【发布时间】: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