使用preventDefault的React / Unit Test(Jest)click方法

时间:2019-08-28 16:02:31

标签: javascript reactjs unit-testing react-test-renderer

所以我遇到了一个小问题……

我有一个Link组件,如果满足特定条件,它将通过to道具转到特定路线。如果不满足该条件,则单击该链接后,它将执行其他操作(以我为例,启动自定义模式)。

我有一个类方法,该方法绑定到我的onClick组件上的Link处理程序

// Card.jsx

import Link from 'components/Link';

...

static props = {
  condition: PropTypes.bool
};

constructor(props) {
  this.state = {
    showModal: false
  };
}

...

goToUrlOrLaunchModal() {
  return (
    <Link
      to="www.google.com"
      onClick={this.handleClick}
    />
  );
}


... 


handleClick(e) {
  const { condition } = this.props;

  if (!condition) {
    e.preventDefault();

    this.setState({
      showModal: true
    });
  }
}

我的问题是单元测试。我有一个单元测试,用于在conditionfalse

时单击链接
// Card.test.js

...

import renderer from 'react-test-renderer';

...

const event = {
  preventDefault: jest.fn()
};

const component = renderer.create(<Card>).getInstance();

instance.handleClick(event);
expect(event.preventDefault).toHaveBeenCalled();
expect(instance.state.showModal).toBe(true);

让我迷路的地方是测试另一面-当conditiontrue时,我不需要调用preventDefault或在那之后执行任何逻辑。我不需要handleClick中的任何东西来解雇。 handleClick中唯一的逻辑是当condition为假时。

单击Link组件时转到路线的逻辑很好,这只是conditiontrue时的单元测试。

我需要测试尚未调用preventDefault,并且将instance.state.showModal设为true,但是我很沮丧。我一直认为这是必须的,但无法超越它……

const event = {
  preventDefault: jest.fn()
};

expect(instance.handleManageClick).not.toHaveBeenCalled();
expect(event.preventDefault).not.toHaveBeenCalled();
expect(instance.state.showModal).toBe(false);

如果有人提供一些指导,将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:1)

感谢Andrew对初始帖子发表评论的帮助,我找到了答案。

这是我所做的:

// Card.test.js

const event = {
  preventDefault: jest.fn()
};

const component = renderer.create(<Card>).getInstance();

const spy = jest.spyOn(instance, 'handleManageClick');

expect(spy).not.toHaveBeenCalled();
expect(event.preventDefault).not.toHaveBeenCalled();
expect(instance.state.showModal).toBe(false);

感谢您的帮助!