【问题标题】:How to test a method which is in mapStateToProps in React using Jest - Enzyme如何使用 Jest - Enzyme 测试 React 中 mapStateToProps 中的方法
【发布时间】:2020-09-17 16:51:14
【问题描述】:

我无法增加此行 handleSave 的覆盖率,我将其作为 prop 传递给我的组件。但是,我在测试用例中从我的容器文件中导入mapStateToProps,并使用.toBeTruthy() 来验证测试用例。

这是我的代码的要点

export const mapStateToProps = (state, ownProps) => {
  return {
    handleSave: title => ownProps.history.push(setTitle(title)),
  };
};

这是我写的测试用例

it('mapStateToProps test case', () => {
  const result = mapStateToProps(state, ownProps);
  expect(result.handleSave).toBeTruthy();
});

有人可以帮忙吗?我应该怎么做才能覆盖handleSave

【问题讨论】:

    标签: javascript reactjs ecmascript-6 jestjs enzyme


    【解决方案1】:

    您可以做的是模拟 ownProps 并测试模拟功能,例如:

    const mockFn = jest.fn();
    const ownProps = {
     history: {
       push: mockFn
     }
    }
    
    const result = mapStateToProps(state, ownProps);
    
    // Now call the handle save function
    result.handleSave("My title");
    
    
    // And then as follows:
    
    // This will ensure that your function is calling ownProps history push method.
    expect(mockFn).toBeCalled();
    
    // To check the funciton has only been called once
    expect(mockFn.mock.calls.length).toBe(1);
    
    
    // This is to check if the correct argument has been passed. Be sure to pass in what your `setTitle` funciton returns 
    expect(mockFn.mock.calls[0][0]).toBe("My title");
    
    

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 2020-05-03
      • 2022-01-18
      • 2020-08-07
      • 1970-01-01
      • 2019-08-12
      • 2018-10-31
      • 2017-04-13
      • 2021-07-29
      相关资源
      最近更新 更多