首页 文章

reactjs - jest snapshot测试嵌套的redux“connected”组件

提问于
浏览
9

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

// User.js

/* ... */

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

/* ... */

export default connect(mapStateToProps)(User);

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

// User.spec.js

import { User } from './User';

/* ... toMatchSnapshot() testing */

但是当连接组件嵌套在另一个连接组件中时,我遇到了问题 . 例如,假设 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);

在_312301上运行快照测试时,就像我在 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)".`

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

1 回答

  • 8

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

    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.
    

    这将使用名为 User 的简单组件替换 User .

相关问题