作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我开始对 React.js 应用程序进行单元测试,我面临的挑战之一是确定组件正确安装所需的所有 Prop 。是否有任何实用程序可以检查成功安装组件所需的一切?此外,这些 Prop 的数据类型可以适本地初始化它们以进行组件渲染。
就像我的一个组件正在使用展开 {...props}
运算符从父级获取 Prop 一样。父级也使用扩展运算符获取这些,然后添加一些额外的 Prop 并将其传递给子级。这使得我很难获得组件期望的所有 Prop 。有没有合法的方法来获取 Prop 列表?
最佳答案
一项有趣的任务。
我从以下开始:
import React from "react";
import * as PropTypes from "prop-types";
function Hello(props) {
const { boo, foo } = props;
return (
<div>
<h1>{boo}</h1>
<h2>{foo}</h2>
</div>
);
}
Hello.propTypes = {
boo: PropTypes.string,
foo: PropTypes.number
};
export default Hello;
我找到这篇文章https://blog.jim-nielsen.com/2020/proptypes-outside-of-react-in-template-literal-components/具有功能:
/**
* Anytime you want to check prop types, wrap in this
* @param {function} Component
* @param {Object} propTypes
* @return {string} result of calling the component
*/
function withPropTypeChecks(Component) {
return props => {
if (Component.propTypes) {
Object.keys(props).forEach(key => {
PropTypes.checkPropTypes(
Component.propTypes,
props,
key,
Component.name
);
});
}
return Component(props);
};
}
然后我又写了一个:
const getPropsInfo = (component) => {
const result = {};
const mock = Object.keys(component.propTypes).reduce(
(acc, p) => ({ ...acc, [p]: Symbol() }),
{}
);
const catching = (arg) => {
const [, , prop, type] = `${arg}`.match(
/Warning: Failed (.*) type: Invalid .* `(.*)` of type `symbol` supplied to.*, expected `(.*)`./
);
result[prop] = type;
};
const oldConsoleError = console.error.bind(console.error);
console.error = (...arg) => catching(arg);
withPropTypeChecks(component)(mock);
console.error = oldConsoleError;
return result;
};
我选择了 Symbol 作为不太预期的类型。
并称其为:
const propsInfo = getPropsInfo(Hello);
console.log(propsInfo);
结果我得到:{boo: "string", foo: "number"}
P.S.:我还没有在其他类型上测试过这一点。只是为了好玩! :)
关于reactjs - React.js : How to get all props component expects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45663097/
我是一名优秀的程序员,十分优秀!