如何使用React Testing Library测试click事件的stopPropagation方法?

3

我有一个简单的Icon组件,它接受一个onClick()属性,在单击图标时调用该函数。另外,每当单击该图标时,还会调用另一个函数event.stopPropagation()。这个函数是由图标触发的实际点击事件的属性(=表示基本)。

现在我想要检查两件事:

  1. onClick属性函数应该被调用。
  2. 通过事件传递的stopPropagation回调应该被调用。

以前我使用enzyme进行测试,效果非常好。

test('Icon should call the callback on when space is pressed', () => {
    const onClick = jest.fn();
    const stopPropagation = jest.fn();
    const icon = shallow(<Icon className="test" name="su-pen" onClick={onClick} />);
    icon.simulate('keypress', {key: ' ', stopPropagation});
    expect(onClick).toBeCalled();
    expect(stopPropagation).toBeCalled();
});

现在我想将它迁移到React测试库。我已经尝试使用fireEvent,但是stopPropagation()没有被调用。

test('Icon should call the callback on click', () => {
    const onClick = jest.fn();
    const stopPropagation = jest.fn();
    render(<Icon className="test" name="su-pen" onClick={onClick} />);
    const icon = screen.queryByLabelText('su-pen');
    fireEvent.click(icon, {stopPropagation});
    expect(onClick).toBeCalled();
    expect(stopPropagation).toBeCalled();
    //                      ^ --> failed
    // Expected number of calls: >= 1
    // Received number of calls:    0
});

当使用enzyme时,您模拟keypress事件,但是当使用RTL时,您触发click事件。它们是不同的事件。 - Lin Du
很抱歉,我可能不太清楚地表达了问题。 - Behemoth
1个回答

1

通过这种方式测试组件的内部而不是它的行为。

我更愿意用一个虚拟元素包装它,并检查在单击图标时是否没有调用其onclick处理程序:

test('Icon should not propagate the click event', () => {
    const onClick = jest.fn();
    const onOuterClick = jest.fn();

    render(
      <div onClick={onOuterClick}>
         <Icon className="test" name="su-pen" onClick={onClick} />
      </div>
    );
    const icon = screen.queryByLabelText('su-pen');
    fireEvent.click(icon);
    
    expect(onClick).toHaveBeenCalledTimes(1);
    expect(onOuterClick).toHaveBeenCalledTimes(0);
});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接