首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >jest中的模拟动画完成回调

jest中的模拟动画完成回调
EN

Stack Overflow用户
提问于 2018-10-24 17:10:05
回答 1查看 4.7K关注 0票数 4

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

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

代码语言:javascript
复制
...
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

代码语言:javascript
复制
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回调?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-25 03:38:55

您可以使用jest.mock模拟模块,如下所示:

代码语言:javascript
复制
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>
    }
}))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52965112

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档