使用Jest在React中测试内联回调函数

时间:2018-06-16 10:00:52

标签: reactjs unit-testing jestjs

我有一个包含以下代码的组件

<Resizable
  ...
  onResizeStop={(e, direction, ref, d) => {
    someFunc(d.width)
  }}
  ...
>

我想测试onResizeStop道具。我可以创建一个新的命名函数并将其分配给prop,但我不太愿意为测试目的更改原始代码。

测试这个道具的理想方法应该是什么。我需要制作模拟功能吗?如何比较实际支柱价值和预期价值?

2 个答案:

答案 0 :(得分:0)

模拟函数通常捕获对函数执行的所有调用,并提供一种方法来检查调用模拟的次数参数它被称为。

Jest的模拟函数make no exception

// Initialize your mock function
const onResizeStopMock = jest.fn();

// Setup your component with React test renderer or Enzyme or any other React renderer tool
<Resizable
  onResizeStop={onResizeStopMock}
>

// Interact with your component and inspect the mock function, eg:

// Mock function was called only once
expect(onResizeStopMock.mock.calls.length).toBe(1);

// Test the fourth argument of the first call ("d")
expect(onResizeStopMock.mock.calls[0][3]).toEqual({width: 99, height: 99});

答案 1 :(得分:0)

对于这个问题还有其他想法吗?

使用上面的代码给出更完整的示例:

class SomeComponent extends React.Component {

  render(){
    return ( <div>
     <Resizable
     ...
     onResizeStop={(e, direction, ref, d) => {
       someFunc(d.width)
     }}
     ...
    >
    </div>)
  }

那么如何测试内部onResizeStop函数呢?

相关问题