首页 > 解决方案 > testing button class with enzyme

问题描述

I have the following button:

import React from 'react';
import PropTypes from 'prop-types';

const Button = ({
  text, url, state, type,
}) => (type === 'link' ?
  <a className="abs3-link" href={url}>{text}</a> :
  <button className={`abs3-button abs3-button--${state}`} type={type}> {text}</button>
);

Button.propTypes = {
  text: PropTypes.string,
  url: PropTypes.string,
  state: PropTypes.oneOf(['default', 'info', 'danger']),
  type: PropTypes.oneOf(['submit', 'reset', 'link']),
};

Button.defaultProps = {
  text: null,
  url: null,
  state: 'default',
  type: 'submit',
};

export default Button;

and I trying to test like this:

import React from 'react';
import { shallow, render, mount, configure } from 'enzyme';
import renderer from 'react-test-renderer';
import Adapter from 'enzyme-adapter-react-16';

import Button from './Button';

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

describe('Button Component', () => {
  test('it should render a button', () => {
    const tree = renderer
      .create(<Button text="Submit" type="submit" state="default" />)
      .toJSON();
    expect(tree).toMatchSnapshot();
  });

  test('it should have a abs3-button--info class', () => {
    const button = shallow(<Button text="Submit" type="submit" state="info" />);
    expect(button.find('.abs3-button').hasClass('abs3-button--info')).to.equal(true);
  });
});

But I'm getting "TypeError: Cannot read property 'equal' of undefined" on my secon test, it's like my button is empty, but I don't undertand why

标签: javascriptreactjsjestjsenzyme

解决方案


我认为您应该使用toEqual(), 并将这一行更改button('.abs3-button').hasClass('abs3-button--info')button.hasClass(abs3-button--info)sincebutton是该组件的根。如果您不确定渲染后组件的外观。您始终可以使用它debug()来打印出组件的渲染结果。

以下是我创建的工作示例create-react-app

test('it should have a abs3-button--info class', () => {
  const button = shallow(<Button text="Submit" type="submit" state="info" />);
  expect(button.hasClass('abs3-button--info')).toBe(true);
});

推荐阅读