我试图用Jest和酶来测试我的反应成分。有些组件中有动画组件(从react-spring/react-motion导入),它将函数呈现为其子函数。这使得测试变得非常困难。我做了很多研究,想出了三个想法:
mount渲染一切,并对其进行快照测试。我发现昂贵的组件是不可能的/无效的,生成的快照通常很重(1MB - 2MB)。shallow和快照测试组分。然后找到动画组件,使用酶的renderProp()渲染里面的子组件,并对它们进行快照测试。在我发现renderProp()与<StaggeredMotion />的react-motion和react-spring没有很好地工作之前,这是非常有效的。解决这个问题的方法是显式地将函数调用为.prop('children')(),然后对整个过程进行浅薄处理,但是代码看起来会很混乱,很难读懂。shallow和快照测试的成分。其他人都站在图书馆那边。问题是:我应该使用哪一个?如果这些都不够好,还有什么可供选择的呢?提前谢谢。
(如果您需要一个代码示例,我非常乐意提供)
发布于 2019-06-05 11:46:05
我解决了测试组件的问题,这些组件通过模仿react来使用react,用于Jest。
为此,将以下内容添加到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)
},
};注意:这些模拟都集中在的呈现支持API上。而且,这种技术将导致忽略所有通常由在测试中生成的内容。(它将创建一个容器<div>。)
https://stackoverflow.com/questions/53953693
复制相似问题