art*_*ras 5 mocking reactjs jestjs react-transition-group
Jest
我正在尝试为React
使用Transition
from的组件编写单元测试react-transition-group
。我需要模拟,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>
)
Run Code Online (Sandbox Code Playgroud)
这是我的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)
})
Run Code Online (Sandbox Code Playgroud)
这个想法是,一旦button
单击 a,组件就会产生动画,然后在完成后触发回调。
如何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>
}
}))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7415 次 |
最近记录: |