反应酶无法测试点击功能

时间:2020-04-04 06:45:12

标签: 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功能。在函数中,我不接受参数或将传递函数的参数作为参数。所以我怎么测试这个功能。抱歉,我的英语让我有点受挫。

1 个答案:

答案 0 :(得分:1)

首先,我很抱歉,因为我只知道如何在React Functions中进行开发。但是,这是一个测试onClick功能的MVP。您只需要在toggleModalVisibilitytitle上声明即可。

您需要模拟toggleModalVisibility,然后找到元素(在您的情况下为div)并执行模拟事件(click),然后在其中进行声明。您不必担心该类文件中的实现细节,因为这无关紧要,只关心预期的输出即可。

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