jest 中的模拟动画完成回调

art*_*ras 5 mocking reactjs jestjs react-transition-group

Jest我正在尝试为React使用Transitionfrom的组件编写单元测试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回调?

Her*_*kov 2

您可以像这样模拟模块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)