开玩笑地模拟动画完成回调



我正在尝试为利用react-transition-groupTransitionReact组件编写一个带有Jest的单元测试。我需要模拟Transition这样我的测试就不必等待动画完成。但是,除了"跳过"动画之外,我还需要onExited回调来触发我的模拟Transition组件。

以下是我的Component.js如何使用Transition

...
return (
<Transition
timeout={1500}
in={this.state.show}
onExited={handleExited}>
{status =>
<button onClick={this.setState({show: false}) className={`component-${status}`}>button</button>
}
</Transition>
)

这是我的Component.test.js

import React from 'react'
import {render, fireEvent} from 'react-testing-library'
import Component from '../Component'
test('check', () => {
const handleCompletion = jest.fn()
const {getByText} = render(
<Component
onButtonClick={handleCompletion}
/>
)
const button = getByText('button')
fireEvent.click(button)
expect(handleCompletion).toHaveBeenCalledTimes(1)
})

这个想法是,一旦单击button,组件就会进行动画处理,然后在完成后触发回调。

如何正确模拟Transition,使其跳过动画但仍触发onExited回调?

你可以像这样用jest.mock模拟模块:

jest.mock('react-transition-group', () => ({
Transition: (props) => {
props.onExited() // you can call it asynchronously too, if you wrap it in a timeout
return <div>
{props.in ? props.children() : null}
</div>
}
}))

最新更新