【问题标题】:React Enzyme - modify internals of shallow rendered functional componentReact Enzyme - 修改浅渲染功能组件的内部结构
【发布时间】:2020-08-15 00:19:11
【问题描述】:

我有一个功能性反应组件,我想在酶单元测试中更改组件内部的属性值(在我的例子中是 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 吗?

【问题讨论】:

    标签: reactjs typescript enzyme


    【解决方案1】:

    这可以通过用 jest 模拟 react-i18next 模块来完成。

    const mockT = jest.fn((a) => a)
    const mockReady = true
    jest.mock('react-i18next', () => 
      jest.fn().mockImplementation(() => ({
        useTranslation: () => ({ t: mockT, ready: mockReady })
      }))
    );
    

    如果您正在使用 ES 模块,请查看 the documentationthis article,或者查看 this answer 以获得其他选项。

    编辑:如果传递一个普通对象,则使用module factory 作为jest.mock 的第二个参数。

    【讨论】:

    • mock的第二个参数是函数而不是对象。
    • 你是对的。我 RTFM 并更新了我的答案。谢谢!
    猜你喜欢
    • 2017-03-11
    • 2016-12-18
    • 2016-10-29
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多