【问题标题】:Mocking animation completion callback in jest开玩笑地模拟动画完成回调
【发布时间】:2019-03-28 15:21:19
【问题描述】:

我正在尝试使用Jest 为使用react-transition-group 中的TransitionReact 组件编写单元测试。我需要模拟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 回调?

【问题讨论】:

    标签: reactjs mocking jestjs react-transition-group


    【解决方案1】:

    您可以像这样使用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>
        }
    }))
    

    【讨论】:

    • 感谢您的建议。但是,props.onExited() 永远不会被调用...我在 handleExitedComponent.js 方法中添加了一个 console.log(),但该消息永远不会被记录。我还检查了当我单击button 时是否调用了setState,并且确实如此。知道它失败的地方吗?我在Component.jest.js 中的const {getByText} = render(... 之前插入了您的代码。
    • 我的代码需要在导入之后但在test('check'...之前进行
    • 如果我在导入后移动你的代码,它会破坏我所有的其他测试 :) 错误说 Warning: Functions are not valid as a React child. 我已经在问题中更新了我的代码示例 - 我忘了包括 @ 的孩子987654333@组件实际上是一个函数{status =&gt; ...}。我应该如何更新您的模拟以使其正常工作?
    • 你需要拨打props.children,我更新了答案
    • 谢谢!我现在可以工作了。只是最后,我将代码更改为Transition: props =&gt; { !props.in &amp;&amp; props.onExited(); return props.children(); },因为我需要始终返回children,并且只有在in 为false 时才需要执行onExited()
    猜你喜欢
    • 2019-04-19
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 2019-11-09
    相关资源
    最近更新 更多