javascript - 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
解决方案
我认为您应该使用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);
});
推荐阅读
- java - 字符串中多个字符串模式的Java正则表达式
- python - 如何将私钥(Pem 格式)保存为 单行字符串
- scala - Neo4j 查询的问题,为之前的匹配结果调用 foreach
- jenkins - Jenkins 系统和 Jenkins 构建中的正确 file.encoding
- ios - 如何检测非侵入式电话
- javascript - Vuetify v-autocomplete 将 [object Object] 显示为初始值(加载前)
- html - Safari:-webkit-line-clamp 不显示省略号
- c++ - 这种编码风格是否属于旧版本的 C++?
- google-apps-script - 谷歌表格宏如何定义范围
- c++ - 有没有办法在正弦方程中设置像“x”这样的“未知”变量,然后改变它的值?