> MyComponent - Render', -6ren">
gpt4 book ai didi

reactjs - 编写 enzyme 测试时何时使用 "Component.WrappedComponent"

转载 作者:行者123 更新时间:2023-12-03 13:26:00 25 4
gpt4 key购买 nike

我正在尝试做什么:

我正在尝试使用shallow按照以下模式从 enzyme 进行渲染,该模式适用于我的项目中的许多其他组件。

describe('>> MyComponent - Render', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<MyComponent.WrappedComponent
actions={{}}
history={}
/>);
});

it("test something", () => { expect(wrapper).toEqual(1); });

});

我遇到了什么问题:

我收到一条错误消息“无法读取未定义的属性“contextTypes””,这意味着 wrapperundefined 。但当我改变 <MyComponent.WrappedComponent />到只是<MyComponent /> ,测试成功。这是我的代码:

describe('>> Legends - render', () => {
let wrapper;

beforeEach(() => {
wrapper = shallow(<Legends textsAndColor={[]} />);
});

it('+++ render the component', () => {
expect(wrapper.length).toEqual(1);
});

it('+++ match snapshot', () => {
expect(wrapper).toMatchSnapshot();
});
});

我有问题:

.WrappedComponent 到底是什么?做 ?为什么 <MyComponent />有效但无效<MyComponent.WrappedComponent />

最佳答案

通过使用.WrappedComponent,您可以访问由redux的connect函数包装的组件。我假设您的大多数组件都是 connect 的(因为使用 .WrappedComponent 没有问题),并且抛出所述错误的组件不是 connect编辑。

我建议您阅读redux docs了解如何为此案例编写测试。简而言之,他们建议对连接组件进行默认导出,对原始组件进行非默认导出。然后仅导入原始组件用于测试目的,如下所示:

import { MyComponent } from './path/to/my/component`;

此后,您将能够挂载(或)您的原始组件,如下所示:

describe('>> MyComponent - Render', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<MyComponent />);
}
});

关于reactjs - 编写 enzyme 测试时何时使用 "Component.WrappedComponent",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com