我运行测试报错:
TypeError: Cannot set property 'background' of undefined
6 | componentDidMount() {
7 | const element = ReactDOM.findDOMNode(this)
> 8 | element.style.background = 'grey'
| ^
9 | }
代码组件:
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
class Test extends Component {
componentDidMount() {
const element = ReactDOM.findDOMNode(this)
element.style.background = 'grey'
}
render() {
return (
<div className="Test">
test
</div>
);
}
}
export default Test;
代码测试:
import React from 'react';
import Link from './Test';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer
.create(<Test/>)
.toJSON();
expect(tree).toMatchSnapshot();
});
这是一个相当简单的组件,据我所知, Jest 无法到达 DOM,我该如何解决这个问题?最简单的事情是我认为这样做是:
element.style && (element.style.background = 'gray')
最佳答案
首先,请注意 ReactDOM.findDOMNode
doc状态:
findDOMNode
is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. It has been deprecated inStrictMode
.
因此应避免使用 findDOMNode
,最好使用 ref
。
话虽如此,测试失败的原因是因为你使用了react-test-renderer
。
overview in the docs说明 react-test-renderer
...
...makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a React DOM or React Native component without using a browser or
jsdom
.
换句话说,react-test-renderer
提供了一个“平台 View 层次结构”类似于 DOM 树,但不提供实际的 DOM 树(或模拟的DOM 树,如 jsdom
)。
所以在这种情况下 element
实际上不是 DOM 元素 并且不包含导致 element.
抛出错误。style
的定义。 style.background
要按照编写的方式测试此代码,您需要使用可呈现为 DOM 树(或模拟 DOM 树)的东西。
最常见的方法之一是使用 Enzyme 中的 mount
它使用 jsdom
提供的模拟 DOM 进行完整的 DOM 渲染:
import React from 'react';
import Test from './Test';
import { mount } from 'enzyme';
it('renders correctly', () => {
const wrapper = mount(<Test />); // renders successfully
...
});
关于reactjs - 不能在测试中设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54855436/