reactjs - 测试是否调用了 const 模态组件

标签 reactjs jestjs enzyme antd

我有一个页脚组件,上面有几个按钮。所有这些按钮都使用 Message 常量,这是一个 antd 模态:

Message.jsx

import { Modal } from 'antd';

const { confirm } = Modal;

export const Message = (text, okayHandler, cancelHandler) => {
  confirm({
    title: text,
    okText: 'Yes',
    cancelText: 'No',
    onOk: okayHandler,
    onCancel: cancelHandler,
  });
};

export default Message;

页脚.jsx

class Footer extends Component {
  state = {
    from: null,
    redirectToReferrer: false,
  };

  cancelClicked = () => {
    Message('Return to the previous screen?', () => {
      this.setState({ redirectToReferrer: true, from: '/home' });
    });
  };

render() {
    const { redirectToReferrer, from } = this.state;

    if (redirectToReferrer) {
      return <Redirect to={{ pathname: from }} />;
    }
    return (
      <Card style={footerSyles}>
        <Button
          bounds={`${(3 * width) / 7 + (7 * width) / 84},5,${width / 7},30`}
          text="CANCEL"
          type="primary"
          icon="close"
          actionPerformed={this.cancelClicked}
        />
</Card>
//actionPerformed is actually onClick, it's taken as a prop from my <Button /> component. Card is an antd component while button is not.

我只是想测试当点击Button 时,cancelClicked 被调用。如果可能的话,我想测试在模态上单击“确定”按钮时状态是否正确更改。我的测试如下,但是因为没有调用函数,所以测试失败了:

Footer.test

const defaultFooter = shallow(<Footer position="relative" bounds="10,0,775,100" />);

test('Footer should open a popup when cancel button is clicked, and redirect to home page', () => {
  const instance = defaultFooter.instance();
  const spy = jest.spyOn(instance, 'cancelClicked');
  instance.forceUpdate();
  const p = defaultFooter.find('Button[text="CANCEL"]');
  p.simulate('click');
  expect(spy).toHaveBeenCalled();
});

我也试过使用 mount 而不是 shallow,但是 spy 仍然没有被调用。

最佳答案

"Common Gotchas" section for simulate说“即使名称暗示这模拟了一个实际事件,.simulate() 实际上会根据您给它的事件定位组件的 Prop 。例如,.simulate('click') 实际上会获得 onClick Prop 并调用它。”

可以在 Enzyme 源代码中看到该行为 herehere .

因此 p.simulate('click'); 行最终尝试调用 ButtononClick 属性它不存在,所以它基本上什么都不做。

This post来自 Airbnb 开发者的建议直接调用 props 并避免 simulate

在这种情况下,您可以像这样直接调用 actionPerformed 属性:

p.props().actionPerformed();

关于reactjs - 测试是否调用了 const 模态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53295027/

相关文章:

reactjs - 测试时,导致 React 状态更新的代码应包装到 act(...)

reactjs - 测试 React 组件方法正在调用函数 pass 作为 prop

reactjs - 在 package.json 中设置主页不会在构建时设置 PUBLIC_URL

javascript - Context API 将状态传递给更高的组件

javascript - React Hooks 的逻辑在哪里?

angular - 在 Jest 单元测试 Angular 中显示正确的错误

reactjs - 如何模拟另一个文件中的返回值?

javascript - 如何使用 Jest 获取代码覆盖率报告?

javascript - 在 Jest 中模拟按钮点击

react-native - 将 Enzyme 与 React Native 一起使用时的错误(导入字形图)