reactjs - 是否可以从 React 测试渲染器中删除主题?
问题描述
我正在使用推荐的 React Native 编写一些单元测试react-test-renderer
,我们的一大堆组件都在使用该react-native-elements
库来提供控件。
然而,我发现,在我的小快照测试中,主题对象是大部分内容,并且更难看到实际的变化。我想知道是否有人知道关闭此功能的方法?
到目前为止,我唯一的想法是将每个测试包装在 a 中ThemeProvider
并为其提供一个空白主题,这是很多样板。
这是一个示例快照
exports[`LocationInfo renders correctly 1`] = `
<Text
style={Object {}}
theme={
Object {
"colors": Object {
"disabled": "hsl(208, 8%, 90%)",
"divider": "#bcbbc1",
"error": "#ff190c",
"grey0": "#393e42",
"grey1": "#43484d",
"grey2": "#5e6977",
"grey3": "#86939e",
"grey4": "#bdc6cf",
"grey5": "#e1e8ee",
"greyOutline": "#bbb",
"platform": Object {
"android": Object {
"error": "#f44336",
"primary": "#2196f3",
"secondary": "#9C27B0",
"success": "#4caf50",
"warning": "#ffeb3b",
},
"ios": Object {
"error": "#ff3b30",
"primary": "#007aff",
"secondary": "#5856d6",
"success": "#4cd964",
"warning": "#ffcc00",
},
},
"primary": "#2089dc",
"searchBg": "#303337",
"secondary": "#8F0CE8",
"success": "#52c41a",
"warning": "#faad14",
},
}
}
>
KEY/100, Main Building
</Text>
`;
解决方案
您可以创建一个 HOC 的模拟,它传递收到的道具并可能添加一些模拟主题
const mockHOC = WrappedComponent => {
const ThemedComponent = (props) => (
<WrappedComponent {...props} theme="omitted" />
);
ThemedComponent.displayName = `MockThemed(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`
return ThemedComponent;
};
1. 可以使用 spyOn 将 mock 实现附加到 withTheme
jest.setup.js
( setupFilesAfterEnv )
import RNE from 'react-native-elements';
const mockHOC = // ....;
jest.spyOn(RNE, 'withTheme').mockImplementation(mockHOC)
2.你可以尝试定义一个全局mock
__mocks__/react-native-elements/config/withTheme.js
const mockHOC = // ....;
export default jest.fn(mockHOC)
推荐阅读
- php - smarty php中的foreach语句
- python-3.x - 如何在 python 中设置堆栈驱动程序日志条目的严重性?
- pandas - 从 Pandas 的数据框列中删除特定对象类型的值
- java - 嵌套 if-else 语句的正确格式
- sql - WHERE a AND b 只返回 WHERE b
- github - Github 完整搜索历史
- typescript - 如何在 TypeScript 中基于另一个创建函数,但修复了一些模板参数
- amazon-web-services - 有没有一种简单的方法可以通过 boto3 重命名 s3 文件夹?
- javascript - 使用 vanilla JS 动态设置暗模式切换按钮
- r - 使用 rvest 登录网站后如何使用 R 注销网站