【问题标题】:Snapshot testing with react-spring/react-motion使用 react-spring/react-motion 进行快照测试
【发布时间】:2018-12-28 04:29:06
【问题描述】:

我正在尝试使用 Jest 和 Enzyme 对我的 React 组件进行快照测试。一些组件中包含动画组件(从react-spring/react-motion 导入),它将一个函数呈现为其子级。这使得测试变得异常困难。我做了很多研究,提出了 3 个想法:

  • 使用 Enzyme 的 mount 渲染所有内容,并对其进行快照测试。我发现昂贵的组件不可能/无效,并且生成的快照通常非常重(1MB - 2MB)。
  • 使用 Enzyme 的shallow 并快照测试组件。然后找到动画组件,使用 Enzyme 的renderProp() 渲染其中的子元素并进行快照测试。这工作得很好,直到我发现renderProp() 不能很好地与<StaggeredMotion /> 配合使用react-motionreact-spring。解决此问题的方法是将函数显式调用为 .prop('children')(),然后将整个代码变浅,但代码看起来很混乱且难以阅读。
  • 只需使用 Enzyme 的shallow 并快照测试组件。其余的都在图书馆那边。

问题是:我应该使用哪一个?如果这些都不够好,还有哪些选择?提前致谢。

(如果您需要代码示例,我很乐意提供)

【问题讨论】:

  • 这个问题你解决了吗?
  • @TimMG 我决定将 react-spring 中的部分提取到不同的组件并进行测试。但是我认为我们不需要通过引入钩子来做到这一点
  • 我按照您的指示为动画部分制作了一个新组件,但我的测试仍然失败。这可能是因为在我要测试的组件中导入了新组件。
  • @TimMG 如果您提出新问题,我将非常乐意回答

标签: reactjs testing enzyme react-motion react-spring


【解决方案1】:

我通过为 Jest 模拟 react-spring 来解决使用 react-spring 测试组件的问题。

为此,请将其添加到您的 Jest 配置中:

[...]
"moduleNameMapper": {
    "^react-spring(.*)$": "<rootDir>/jest/react-spring-mock.js"
},

文件/jest/react-spring-mock.js 可能如下所示:

const React = require('react');

function renderPropsComponent(children) {
    return React.createElement('div', null, children()({}));
}

export function Spring(props) {
    return renderPropsComponent(props.children);
};

export function Trail(props) {
    return renderPropsComponent(props.children);
};

export function Transition(props) {
    return renderPropsComponent(props.children);
};

export function Keyframes(props) {
    return renderPropsComponent(props.children);
};

export function Parallax(props) {
    return renderPropsComponent(props.children);
};

export const animated = {
    div: (props) => {
        return React.createElement('div', null, props.children)
    },
};

注意:这些模拟集中在 react-spring 的 render-props API 上。 此外,此技术将导致忽略测试中通常由 react-spring 生成的所有内容。 (它将创建一个容器&lt;div&gt;。)

【讨论】:

  • 听起来不错。你试过新的钩子api吗?
  • 我还没有,但我会的。我想他们可以以类似的方式被嘲笑。类似export const useSpring = () =&gt; [{}, () =&gt; {}];
猜你喜欢
  • 2017-10-01
  • 2021-10-05
  • 2021-05-27
  • 2018-12-17
  • 2017-05-25
  • 2019-07-26
  • 1970-01-01
  • 2019-02-15
  • 2018-08-01
相关资源
最近更新 更多