reactjs - React Enzyme - 修改浅渲染功能组件的内部结构
问题描述
我有一个功能性反应组件,我想在酶单元测试中更改组件内部的属性值(在我的情况下是ready
属性)。应该使用单元测试shallow
来避免渲染任何子组件。
这是简化的组件代码:
import {useTranslation} from 'react-i18next';
// ...
const MyComponent: React.FC<IProps> = (props: IProps) => {
const {t, ready} = useTranslation('my-translation-namespace');
// ...
return (
<React.Fragment>
{ready &&
<div className="my-component">some more content...</div>
}
</React.Fragment>)
};
export default MyComponent;
这是相应的测试:
describe('MyComponent', () => {
let component: ShallowWrapper;
it('should be displayed', () => {
component = shallow(<MyComponent/>);
// HERE I WOULD LIKE TO SET: component.ready = true
expect(component.find('.my-component').length).toBe(1);
});
});
知道如何ready
在我的测试中将属性更改为 true 吗?
解决方案
这可以通过react-i18next
用 jest 模拟模块来完成。
const mockT = jest.fn((a) => a)
const mockReady = true
jest.mock('react-i18next', () =>
jest.fn().mockImplementation(() => ({
useTranslation: () => ({ t: mockT, ready: mockReady })
}))
);
如果您正在使用 ES 模块,请查看文档或本文,或者查看其他选项的答案。
编辑:如果传递一个普通对象,则使用模块工厂作为第二个参数。jest.mock
推荐阅读
- c# - C# - 从 SHarepoint 内部发送电子邮件
- ios - CallKit 防止 PushKit 被调用
- android - Android SDK 不是 VS 2017 上安装的属性
- php - 如何从数组中的键和值中删除/替换某些字符?
- r - 使用for循环和if语句从数据框中的变量创建列联表列表?
- typescript - 打字稿泛型函数重载
- java - 插入 oracle 数据库时出现 NullPointerException
- python - Django URL,在 URL 中传递参数
- google-apps-script - Google sheet 的脚本操作不可靠
- mysql - 在mysql中生成序列号