gpt4 book ai didi

javascript - TypeError : Cannot read property 'scrollIntoView' of null - react. Jest 酵素

转载 作者:行者123 更新时间:2023-11-28 21:01:55 25 4
gpt4 key购买 nike

使用 react 16.3.1、jest 16.3.1、enzyme 3.3.0。

在我的 React Class 组件中,我创建了一个 React ref,我用它来确保在安装组件时浏览器位于页面顶部。

class PageView extends React.Component {

constructor(props) {
super(props);
this.topOfPageRef = React.createRef();
}

componentDidMount() {
ReactDOM.findDOMNode(this.topOfPageRef.current).scrollIntoView();
}

render(){
const { x } = this.props;

return (
<React.Fragment>
<div className="main-wrapper" ref={this.topOfPageRef}>
Top
</div>
)}
</React.Fragment>
);
}
}

这一切都在浏览器中完美运行,但在我的 enzyme 测试中失败了。

我的测试很简单,它只是尝试渲染组件。

  it('should render component correctly', () => {
const props = {
...defaultProps,
};
const wrapper = mount(<PageView {...props} />);
expect(wrapper).toMatchSnapshot();
});

TypeError: 无法读取 null 的属性“scrollIntoView”

我已经尝试了 shallowmount 方法,虽然找到的元素不为空,但它似乎是 HTMLDivElement 的一个 react 实例,它缺少 scrollIntoView 方法。

最佳答案

错误信息说明

像上面的示例代码一样使用 mount 会出现此错误:

TypeError: _reactDom2.default.findDOMNode(...).scrollIntoView 不是函数

使用 shallow 给出上面列出的错误:

TypeError:无法读取 null 的属性“scrollIntoView”


问题

shallow 不进行 DOM 渲染,因此永远不会有可在其上调用 scrollIntoView() 的 DOM 节点。

解决方案

任何执行 DOM 操作的代码都需要使用 mount 提供的完整 DOM 渲染进行测试。


挂载

"The default environment in Jest is a browser-like environment through jsdom" .

"jsdom is a pure-JavaScript implementation of many web standards...[that] emulate[s] enough of a subset of a web browser to be useful for testing" .

问题

jsdom 实现了大部分的浏览器环境,但它并没有实现所有的东西。这个问题需要特别注意的是,它没有实现 scrollIntoView,因为 jsdom does not do layout and would therefore not be able to provide an accurate implementation .

因为 jsdom 没有实现 scrollIntoView 它在 jsdom 提供的元素上将是未定义的。

解决方案

recommended approach from this Google dev是将以下行添加到您的测试代码中:

Element.prototype.scrollIntoView = () => {};

该行会将 scrollIntoView 的 noop 实现添加到 jsdom 提供的 Element

对于您的测试,您可以更进一步并将 scrollIntoView 设置为 spy 以确保它被调用:

it('should render component correctly', () => {
const props = {
...defaultProps,
};
Element.prototype.scrollIntoView = jest.fn(); // set scrollIntoView to a spy
const wrapper = mount(<PageView {...props} />);
expect(wrapper).toMatchSnapshot();
expect(Element.prototype.scrollIntoView).toHaveBeenCalled(); // PASSES
});

此外,Antonio 是正确的,您不需要使用 ReactDOM.findDOMNode(),您应该能够直接使用 this.topOfPageRef.current:

componentDidMount() {
this.topOfPageRef.current.scrollIntoView();
}

关于javascript - TypeError : Cannot read property 'scrollIntoView' of null - react. Jest 酵素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52331990/

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