【问题标题】:Check if the function is triggered in ReactJS检查函数是否在 ReactJS 中触发
【发布时间】:2021-09-08 18:05:59
【问题描述】:

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

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

【问题讨论】:

  • 我以前没用过jest,但不应该是 jest.spyOn(DEMO.test.hi, 'hi') 吗? (您缺少 .hi 作为方法名称)
  • 我在本地试了一下,测试通过,没有问题。你能发布你的整个测试代码吗?
  • @Ibsn,我试图测试这个逻辑codesandbox.io/s/pk9yb,基本上是下一个想法,用户点击按钮,应该会出现来自message.info('This is a normal message');This is a normal message。 Tryng const spyOnFun = jest.spyOn(message, 'info'); 我接到 0 个电话。可能是什么问题?

标签: reactjs jestjs enzyme


【解决方案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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多