reactjs - jest快照测试嵌套的redux"连接"组件

psh*_*hah 11 reactjs jestjs redux

当快照测试(jest快照)连接到redux存储的组件时,我可以导出除连接组件之外的实际组件

// User.js

/* ... */

export class User extends React.Component {/* ... */}

/* ... */

export default connect(mapStateToProps)(User);
Run Code Online (Sandbox Code Playgroud)

在测试文件中,我可以导入实际组件(而不是连接的版本)并对其进行快照测试.

// User.spec.js

import { User } from './User';

/* ... toMatchSnapshot() testing */
Run Code Online (Sandbox Code Playgroud)

但是当连接组件嵌套在另一个连接组件中时,我遇到了问题.例如,假设User组件嵌套在另一个连接的组件中 -

// Wrapper.js

import User from './User'; // importing the connected version

/* ... */

export class Wrapper extends React.Component {

  /* ... */

  render() {
    return (
      <div>
        /* ... */
        <User />
      </div>
    );
  }
}

export default connect(mapStateToProps)(Wrapper);
Run Code Online (Sandbox Code Playgroud)

Wrapper我以同样的方式运行快照测试时User给出了以下错误:

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

快照时有没有办法浅渲染?或者我做错了什么?

And*_*rle 10

在这种情况下,最好的方法是Wrapper通过模拟来测试它自己User

import Wrapper from './Wrapper'

jest.mock('./User', () => 'User') // note that the path to user is relative the test file not to  the Wrapper.js file.
Run Code Online (Sandbox Code Playgroud)

这将替换User为带有名称的简单组件User.