Javascript 用酶测试按钮类

Javascript 用酶测试按钮类,javascript,reactjs,jestjs,enzyme,Javascript,Reactjs,Jestjs,Enzyme,我有以下按钮: 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-b

我有以下按钮:

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;
从“React”导入React;
从“道具类型”导入道具类型;
常量按钮=({
文本、url、状态、类型、,
})=>(类型==='link'?
:
{text}
);
Button.propTypes={
text:PropTypes.string,
url:PropTypes.string,
状态:PropTypes.oneOf(['default'、'info'、'danger']),
类型:PropTypes.oneOf(['submit'、'reset'、'link']),
};
Button.defaultProps={
文本:空,
url:null,
声明:“默认值”,
键入:“提交”,
};
导出默认按钮;
我试着这样测试:

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);
  });
});
从“React”导入React;
从“酶”导入{shall,render,mount,configure};
从“反应测试渲染器”导入渲染器;
从'enzyme-Adapter-react-16'导入适配器;
从“./按钮”导入按钮;
配置({adapter:newadapter()});
描述('按钮组件',()=>{
test('它应该呈现一个按钮',()=>{
常量树=渲染器
.create()
.toJSON();
expect(tree.toMatchSnapshot();
});
test('它应该有一个abs3按钮--info类',()=>{
常量按钮=浅();
expect(button.find('.abs3 button').hasClass('abs3-button--info')).to.equal(true);
});
});

但是在我的secon测试中,我得到了“TypeError:无法读取未定义属性'equal',这就像我的按钮是空的,但我不明白为什么我认为你应该使用
toEqual()
,并将这行
按钮('.abs3按钮').hasClass('abs3-button--info')
更改为
button.hasClass(abs3-button--info)
因为
按钮
是此组件的根。如果不确定渲染后组件的外观。始终可以使用
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);
});
test('它应该有一个abs3按钮--info类',()=>{
常量按钮=浅();
expect(button.hasClass('abs3-button--info')).toBe(true);
});

console.log(button.find('.abs3 button'))
results?ReactWrapper{length:1}