gpt4 book ai didi

javascript - 如何测试包裹在另一个连接组件中的连接组件?

转载 作者:行者123 更新时间:2023-11-30 14:02:31 24 4
gpt4 key购买 nike

我想测试我的纯组件,所以我这样做:

MyComp.js

export MyComp = props => {
return (
<Wrapper>Content</Wrapper>
)
}

const MyCompConn = connect()(MyComp);
export default MyCompConn;

哪里<Wrapper> :

export Wrapper = ({children}) => {
return (
<div>{children}</div>
)
}

const WrapperConn = connect()(Wrapper);
export default WrapperConn;

MyComp.test.js

import React from 'react';
import renderer from 'react-test-renderer';

import { MyComp } from '../../MyComp';


describe('With Snapshot Testing', () => {
it('renders!"', () => {
const component = renderer.create(<Login />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});

现在,当我运行 yarn test 时我收到此错误:

Invariant Violation: Could not find "store" in either the context or props of "Connect(AppWrapper)". Either wrap the root component in a <Provider> or explicitly pass "store" as a prop to "Connect(AppWrapper)"

发生这种情况是因为 <Wrapper>已连接到我的 <MyComp>组件,但我不确定如何测试后者,即使它包装在连接的组件上。

最佳答案

为了在不使用模拟存储的情况下测试我们的组件,我们可以使用 Jest 来模拟 React-Redux 本身的连接。 PFB示例:


import React from 'react';
import renderer from 'react-test-renderer';

import { MyComp } from '../../MyComp';

jest.mock('react-redux', () => ({
connect: () => {
return (component) => {
return component
};
}
}));

describe('With Snapshot Testing', () => {
it('renders!"', () => {
const component = renderer.create(<Login />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});

现在,这将直接渲染 Wrapper 组件,而不是连接的 Wrapper 组件。

关于javascript - 如何测试包裹在另一个连接组件中的连接组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56072428/

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