首页 > 解决方案 > 测试uisng酶时如何读取节点中的孩子

问题描述

我有一个组件,我想测试 click 方法。我正在使用浅,但我的测试失败了,因为它找不到按钮,因此它是点击方法。我的代码有什么问题?

interface IProps {
  label: string;
  className: string;
  onClick: () => void;
}

export const NewButton: React.StatelessComponent<IProps> = props => {
  return (
    <Button type="button" className={props.className} onClick={props.onClick}>
      {props.label}
    </Button>
  );
};

import { shallow } from 'enzyme';
import * as React from 'react';
import { NewButton } from "../Buttons";

describe('<NewButton />', () => {
    describe('onClick()', () => {
      const props = {
        className: "buttonSubmit",
        label: "submit",       
        onClick: () => {},
      }
      test('successfully calls the onClick handler', () => {
        const mockOnClick = jest.fn();
        const wrapper = shallow(
          <NewButton {...props}  />
        );
        const button = wrapper.find('submit').dive();
        expect(button.exists()).toEqual(true)   
        button.simulate('click');
        expect(mockOnClick.mock.calls.length).toBe(1);
      });
    });
  });

调试模式下的节点描述

标签: reactjsjestjsenzyme

解决方案


由于您使用的是shallow方法,它只会渲染我们正在测试的组件。它不渲染子组件。因此,您应该尝试找到该Button组件。

const button = wrapper.find('Button');

之后,您应该模拟props.onClick作为道具传递给NewButton组件的事件处理程序。

const props = {
   className: "buttonSubmit",
   label: "submit",       
   onClick: jest.fn(),
}

所以你可以使用

 describe('<NewButton />', () => {
    describe('onClick()', () => {
      const props = {
        className: "buttonSubmit",
        label: "submit",       
        onClick: jest.fn(),
      }
      test('successfully calls the onClick handler', () => {
        const wrapper = shallow(
          <NewButton {...props}  />
        );
        const button = wrapper.find('Button');
        expect(button.exists()).toEqual(true)   
        button.simulate('click');
        // Since we passed "onClick" as props
        // we expect it to be called when 
        // button is clicked
        // expect(props.onClick).toBeCalled();
        expect(props.onClick.mock.calls.length).toBe(1);
      });
    });
  });

推荐阅读