gpt4 book ai didi

javascript - 在 Enzyme 中测试 DOM

转载 作者:行者123 更新时间:2023-11-28 21:07:52 26 4
gpt4 key购买 nike

假设我有一个像这样的小组件:

Button.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>
);
}
}

还有一些像这样的 super 基本样式:

Button.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;
}

假设我想为此编写一些测试:

Button.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);
});

我已经使用 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');
});

但是 background 返回空白,事实上,如果我执行 console.log(getCompulatedStyle(domNode)) 我得到的返回值似乎缺少样式:

  console.log src/modules/Button/Button.test.js:42
CSSStyleDeclaration {
_values: {},
_importants: {},
_length: 0,
_onChange: [Function] }

最佳答案

enzyme 包装器的 getDOMNode 可以获取相应的 DOM 节点。

然后您可以使用 getCompulatedStyle 获取该 DOM 的样式:

const renderedComponent = mount(<MyComponent /);
const domNode = renderedComponent.find('div').at(0).getDOMNode();
const background = getComputedStyle(domNode).getPropertyValue('background');
expect(background).toBe('red');

关于javascript - 在 Enzyme 中测试 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51024736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com