检查函数是否在 ReactJS 中触发

IT技术 reactjs jestjs enzyme
2021-05-22 04:57:00

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

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 并且我的测试没有通过。
有什么问题可以解决?

1个回答

根据您的问题工作,您可以在对象上使用 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/