如何使用Jest-Enzyme在React中测试mapStateToProps中的方法

问题描述 投票:0回答:1

我无法增加此行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 enzyme jest
1个回答
0
投票

您可以做的是模拟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");

© www.soinside.com 2019 - 2024. All rights reserved.