Ste*_*ame 2 javascript testing reactjs enzyme
假设我有一个像这样的小组件:
按钮.js
import React from 'react';
import './Button.css';
export default class Button extends React.Component {
render() {
return (
<a href={ this.props.url } className={`button button-${ this.props.type }`}>
{ this.props.content }
</a>
);
}
}
Run Code Online (Sandbox Code Playgroud)
还有一些超级基本的样式,如下所示:
按钮.css
.button {
color: white;
padding: 1em;
border-radius: 5px;
text-decoration: none;
}
.button-primary {
background-color: red;
}
.button-primary:hover {
background-color: darkred
}
.button-secondary {
background-color: aqua;
color: black;
}
.button-secondary:hover {
background-color: darkcyan;
color: white;
}
Run Code Online (Sandbox Code Playgroud)
假设我想为此编写一些测试:
按钮.test.js
import React from 'react';
import Enzyme, {shallow, mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({adapter: new Adapter()});
import Button from './Button';
import './Button.css';
// Render buttons
const primaryButton = mount(
<Button
content="Primary button"
url="http://www.amazon.co.uk"
type="primary"
/>
);
const secondaryButton = mount(
<Button
content="Secondary button"
url="http://www.ebay.co.uk"
type="secondary"
/>
);
it('should exist', () => {
expect(primaryButton).toBeDefined();
expect(secondaryButton).toBeDefined();
});
it('should display text in the button', () => {
expect(primaryButton.text()).toEqual('Primary button');
});
it('should have the correct CSS classes', () => {
expect(primaryButton.find('.button').hasClass('button-primary')).toEqual(true);
expect(secondaryButton.find('.button').hasClass('button-secondary')).toEqual(true);
});
Run Code Online (Sandbox Code Playgroud)
我已经使用它进行了设置react-create-app,并且上述所有内容都完美运行。
我的问题是:如何测试渲染的内容是否正确?例如,在本例中,我想确保按钮具有 CSS 文件中定义的正确背景颜色,并且具有正确的边框半径。例如,这将防止其他开发人员意外覆盖关键样式。
我的印象是 Enzyme 是开箱即用的,但我无法理解如何询问我认为在后台发生的虚拟 DOM?我认为 JSDOM 会自动运行,并且我是从作为 Node 环境的 CLI 执行的。
到目前为止我已经尝试过:
it('should have the correct background colours', () => {
const domNode = primaryButton.find('.button').at(0).getDOMNode();
const background = getComputedStyle(domNode).getPropertyValue('background');
expect(background).toBe('red');
});
Run Code Online (Sandbox Code Playgroud)
但background返回空白,事实上,如果我这样做,console.log(getComputedStyle(domNode))我会返回它,这似乎缺少样式:
console.log src/modules/Button/Button.test.js:42
CSSStyleDeclaration {
_values: {},
_importants: {},
_length: 0,
_onChange: [Function] }
Run Code Online (Sandbox Code Playgroud)
酶包装器的getDOMNode可以让你获得相应的 DOM 节点。
然后你可以使用getComputedStyle 来获取该 DOM 的样式:
const renderedComponent = mount(<MyComponent /);
const domNode = renderedComponent.find('div').at(0).getDOMNode();
const background = getComputedStyle(domNode).getPropertyValue('background');
expect(background).toBe('red');
Run Code Online (Sandbox Code Playgroud)