javascript - React enzyme 无法测试 onclick 功能

标签 javascript reactjs jestjs enzyme

] 1

这是我在该图像中的组件的完整代码和测试代码

import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import ProfileCard from '../profileCard';
import Adapter from 'enzyme-adapter-react-16';
import InfoCard from '../infoCard';
import renderer from 'react-test-renderer';

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

describe('Profile Card', () => {
  const props = {
    percentageCompleted: 20,
    toggleModalVisibility: () => console.log(''),
    title: 'Value From Test',
    icon: 'string',
    active: false
  };
  const component = mount(<InfoCard {...props} />);

  it('onclick function should toggle model visibality', () => {
    const wrapper = shallow(<InfoCard {...props} />).instance();
    const preventDefaultSpy = jest.fn();
    expect(component.props().title.length).toBe(15);
    //wrapper.onClick  //i am stuck here
    console.log('what is in there', wrapper);
  });

  // it('should render correctly', () => {
  //   const tree = renderer.create(<InfoCard {...props} />).toJSON();
  //   expect(tree).toMatchSnapshot();
  // });

  it('icon shpuld be equal to prop icon', () => {
    expect(component.find('img').prop('src')).toEqual(props.icon);
  });
});

因为我不知道如何测试 onClick 函数。在函数中,我没有将参数或其他东西作为参数传递到函数中。那么我该如何测试这个功能呢?对不起我的英语,因此我有点沮丧。

最佳答案

首先我很抱歉,因为我只知道如何在 React Functions 中进行开发。但这里有一个 MVP 来测试 onClick 功能。您只需对 toggleModalVisibilitytitle 进行断言即可。

您需要模拟 toggleModalVisibility,然后找到元素(在您的情况下为 div)并执行模拟事件(click) code>) 并在那里进行断言。您无需担心该类文件中的实现细节,因为这并不重要,您只关心预期的输出。

import { shallow } from "enzyme";
import React from "react";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import InfoCard from "../src/InfoCard";

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

const toggleModalVisibility = jest.fn();

const initialProps = {
  toggleModalVisibility,
  title: "My title",
  active: true
};
const getInfoCard = () => {
  return shallow(<InfoCard {...initialProps} />);
};

let wrapper;

beforeEach(() => {
  toggleModalVisibility.mockClear();
});
it("should call toggleModalVisiblity when onClick", () => {
  wrapper = getInfoCard();

  wrapper.find("div#myDiv").simulate("click");

  expect(toggleModalVisibility).toHaveBeenCalledWith(initialProps.title);
});

Edit React Jest and Enzyme Testing

关于javascript - React enzyme 无法测试 onclick 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61024664/

相关文章:

javascript - 预计 toHaveBeenCalledWith 不适用于最新的 CreateReactApp 设置

unit-testing - 如何在带有 Jest 的 react-native 中使用模拟的 fetch() 对 API 调用进行单元测试

javascript - Facebook JavaScript API : '/me/albums' not working for other users

javascript - 如何检测网页上的空白区域

javascript - 循环问题 javascript 将无法运行

javascript - 类型的 React PropType 元素

reactjs - react native 平面列表逆序

javascript - ( react )对可能为空的对象数组进行类型检查的正确方法?

javascript - AngularJS:日期输入仅在 Chrome 中显示

javascript - 使用 react-testing-library 时如何测试组件是否使用正确的 props 渲染?