首页 > 解决方案 > 检查函数是否在 ReactJS 中触发

问题描述

我的反应应用程序中有这个组件:

export const DEMO = {
  test: {
    hi: (txt) => console.log(txt)
  }
}

export default function App() {
  
  const getAlert = (c) => {
    DEMO.test.hi('hello');
  }
  
  return (
    <div className="App">
      <button onClick={getAlert}>open alert</button>
    </div>
  );
}
基本上,当我按下按钮时,我触发了 console.log 文本的功能。我还使用酶和玩笑为这个组件创建了一个测试。

it('should trigger calls', () => {
    const spyOnFun = jest.spyOn(DEMO.test, 'hi');

    const wrapper = shallow(
      <App/>,
    );
     wrapper.find('button').simulate('click');
    
    expect(spyOnFun).toHaveBeenCalledTimes(1); //expect 1 but get 0
  });

你怎么能看到我监视了这个方法jest.spyOn(DEMO.test, 'hi');,我希望在点击后得到 1 个调用,但是我得到了 0 并且我的测试没有通过。
可能是什么问题和锄头要解决?

标签: reactjsjestjsenzyme

解决方案


根据您的问题,您可以在对象上使用 spyOn:

// App.js
import React from "react";
import { Button } from "antd";

export const DEMO = {
  test: {
    hi: (txt) => console.log(txt)
  }
};

const info = () => {
  DEMO.test.hi("hello");
};

export function App() {
  return (
    <Button type="primary" onClick={info}>
      Display normal message
    </Button>
  );
}

并为您的测试:

// App.test.js
import React from "react";
import { configure, shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";

import { App, DEMO } from "./App";

configure({ adapter: new Adapter() });

it("should trigger calls", () => {
  const spy = jest.spyOn(DEMO.test, "hi");
  const wrapper = shallow(<App />);
  wrapper.find("Button").simulate("click");
  expect(spy).toHaveBeenCalledTimes(1);
});

工作演示:https ://codesandbox.io/s/enzyme-spy-on-m3s42

作为建议,React 社区远离了浅层渲染,您应该考虑在您的项目中使用https://testing-library.com/docs/react-testing-library/intro/


推荐阅读