首页 > 解决方案 > 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 吗?

标签: reactjstypescriptenzyme

解决方案


这可以通过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


推荐阅读