快照测试使用PropTypes的React连接组件

时间:2018-09-10 21:06:48

标签: reactjs react-redux jestjs enzyme

我的React App中有一个组件,该组件通过react-redux和两个道具相连

import PropTypes from "prop-types";
import { createNewPlayer } from "../actions/AllActions";
class HomePage extends React.Component {...}
HomePage.propTypes = {
  createNewPlayer: PropTypes.func.isRequired,
  history: PropTypes.shape({
    push: PropTypes.func.isRequired
  }).isRequired
};
export default connect(null,{ createNewPlayer })(HomePage);

在index.js,我有ReactDOM.render(<BrowserRouter><Provider store={store}> ...)

和App.js const App = () => (<Route path="/" exact component={HomePage} />);export default App;

使用我已经写过的JestEnzyme对主页进行快照测试

import React from "react";    
import toJSON from "enzyme-to-json";    
import { shallow, mount } from "enzyme";
import HomePage from "../components/HomePage";

test("should render the HomePage Component", () => {
  const props = { createNewPlayer: jest.fn(), push: jest.fn() };
  const wrapper = mount(shallow(<HomePage {...props} />));
  expect(toJSON(wrapper)).toMatchSnapshot();
});

出现错误的地方

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

我应该如何用proptype快照测试连接的组件

2 个答案:

答案 0 :(得分:0)

对于您的示例测试,由于您仅在测试中引用了App,因此您似乎并没有尝试从HomePage向下测试整个集成。这样,除了默认的connect导出,您还可以导出该类进行测试。因此,您的测试将使用import { HomePage } from '...';,而其他组件将使用默认的import HomePage from '...';

答案 1 :(得分:0)

您不应测试连接的组件。我们想要测试未连接的版本,因为我们希望能够提供一组动态道具。道具就是数据。在测试环境中,您应该在/ tests目录中创建一个/ fixture目录。您应该将基准数据或虚拟数据保留在该目录中,然后将其导出。或者,您也可以在测试文件中创建数据,但这会造成混乱。

export class HomePage extends React.Component {...}

在测试文件中

import React from "react";    
import toJSON from "enzyme-to-json";    
import { shallow, mount } from "enzyme";
import {HomePage} from "../components/HomePage";
import props from "../fixtures/createNewPlayer" //in here you should put your data

test("should render the HomePage Component", () => {
  //const props = { createNewPlayer:jest.fn(), push: jest.fn(); IMPORTED ALREADY
  const wrapper = mount(shallow(<HomePage {...props} />));
  expect(toJSON(wrapper)).toMatchSnapshot();
});