首页 > 解决方案 > 在 react-redux 连接组件中进行单元测试时出错

问题描述

我正在尝试用 jest-enzyme 测试连接的组件(react-redux)。我正在使用 react-redux-mock 商店。当我运行测试以在组件中找到一个 div 时,它给了我这个错误。

Invariant Violation: Passing redux store in props has been removed and does not do anything. To use a custom Redux store for specific components, create a custom React context with React.createContext(), and pass the context object to React-Redux's Provider and specific components like: <Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>. You may also pass a {context : MyContext} option to connect

我确实安装并测试了没有 redux 的组件,它可以工作,但我想做一个 > 浅测试。

describe("Input Component", () => {
let wrapper;
let store;
beforeEach(() => {
    store = mockStore(initialState);

    wrapper = shallow(<Input store={store} />);
});

it("should rendder without error", () => {
    expect(wrapper.find("div")).toHaveLength(1);
});
});

标签: reactjsreact-reduxjestjsenzymeconnected-components

解决方案


你如何导入你的组件?

例如,如果您使用 import App from './yourpath/App' 导入它,那么实际上您持有的是 connect() 返回的包装器组件,而不是 App 组件本身。

为了能够在不处理装饰器的情况下测试 App 组件本身,您还必须导出未装饰的组件:

import { connect } from 'react-redux'

// Use named export for unconnected component (for tests)
export class App extends Component {
/* ... */
}

// Use default export for the connected component (for app)
export default connect(mapStateToProps)(App)

并将其导入您的测试文件中,如下所示:

import { App } from './yourpath/App'

推荐阅读