Reactjs 如何测试React类组件中componentDidMount期间调用Redux分派函数?

Reactjs 如何测试React类组件中componentDidMount期间调用Redux分派函数?,reactjs,testing,redux,jestjs,react-testing-library,Reactjs,Testing,Redux,Jestjs,React Testing Library,以下是我的基本设置: 我有一个React类组件 使用connect()连接到我的Redux存储的 在componentDidMount期间激发函数的 该函数是组件通过mapDispatchToProps(隐式)访问的函数 我想测试一下上述方法是否有效,在这种情况下,fetchComments会在componentDidMount生命周期中调用特定的函数,甚至是我的组件 以下是相关部件代码: class CommentContainer extends React.Component{ com

以下是我的基本设置:

  • 我有一个React类组件
  • 使用connect()连接到我的Redux存储的
  • 在componentDidMount期间激发函数的
  • 该函数是组件通过mapDispatchToProps(隐式)访问的函数
  • 我想测试一下上述方法是否有效,在这种情况下,
    fetchComments
    会在
    componentDidMount
    生命周期中调用特定的函数,甚至是我的组件

    以下是相关部件代码:

    class CommentContainer extends React.Component{
      componentDidMount(){
        this.props.fetchComments(this.props.resourceId)
      }
    
    ...
    
    export default connect(mapStateToProps, { authorizeUser, addComment, fetchComments })(CommentContainer)
    
    对于测试,我尝试了很多不同的方法。我唯一能做的事情不是测试
    fetchComments
    是否被调用(据我所知,这是隔离功能的最佳方式),而是测试存储是否以特定方式更新(只有在调用
    fetchComments
    时才会发生)

    我的测试是有效的:

    import { render } from '@testing-library/react'
    
    ...
    
    it ('loads comments upon rendering', ()=> {
      const store = createStore(rootReducer, applyMiddleware(thunk)) //I've also tried mockStores, but that didn't seem to work well with the connect() method in the component
      expect(store.getState().comments.loadStatus).toBe(null)
      render(<Provider store={store}>
              <Router>
                  <CommentContainer 
                    relativePath={"/resources/:id"} 
                    resourceId={1}
                  />
                </Router>
              </Provider>
            )
      expect(store.getState().comments.loadStatus).not.toBe(null)
    }
    
    我推测这是因为在幕后,
    store.dispatch
    通过了一个匿名函数,该函数的“工作”是
    fetchComments
    ,但没有通过实际函数
    fetchComments
    。准确吗

    除其他外,我还尝试创建了一个模拟函数
    fetchComments
    ,并将其作为一个道具直接传递给
    CommentContainer
    ,但该道具似乎被
    connect()
    方法和
    mapDispatchToProps
    覆盖了

    我尝试的另一件事是使用Enzyme和
    shallow
    mount
    而不是react测试库的
    render
    ,然后使用
    .props()
    方法从
    CommentContainer
    中检索
    fetchComments
    ,但当我这样做时,我得到一个错误,即prop是“只读的”所以我不能做类似于
    jest.spyOn(wrapper.props,'fetchComments')

    我很感激任何关于如何使这项工作或我应该如何测试这项功能的反馈

    const spy = jest.spyOn(store, "dispatch")
    render(<Provider store={store}>
                <Router>
                <CommentContainer 
                  relativePath={"/resources/:id"} 
                  resourceId={1}
                />
              </Router>
            </Provider>
            )
    expect(spy).toHaveBeenCalledWith(fetchComments)
    
    Expected: [Function fetchComments]
        Received
               1: [Function anonymous]
               2: [Function anonymous]