我正在尝试用Jest
为一个使用来自react-transition-group
的Transition
的React
组件编写一个单元测试。我需要模拟Transition
,这样我的测试就不必等待动画完成。但是,除了“跳过”动画之外,我还需要在模拟的Transition
组件上触发onExited
回调。
下面是我的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
回调?
发布于 2018-10-25 03:38:55
您可以使用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>
}
}))
https://stackoverflow.com/questions/52965112
复制相似问题