gpt4 book ai didi

reactjs - React ref.current 仅在 Enzyme 测试中在 componentDidMount 中为 null,实时情况下不为 null

转载 作者:行者123 更新时间:2023-12-03 13:49:32 27 4
gpt4 key购买 nike

我对测试 React 组件相当陌生,并且正在努力测试使用 React.createRef 创建的引用。我已经阅读了这篇精彩的回复 我不确定它是否解决了我的问题。 componentDidMount called BEFORE ref callback

constructor(props) {
super(props);
this.myRef = React.createRef();
console.log('this.myRef in constructor', this.myRef);
}

此控制台日志返回 null,这是预期的,因为组件尚未呈现。

componentDidMount() {
console.log('this.myRef in component did mount', this.myRef);
}
    return (
<div className="tab_bar">
<ul ref={this.myRef} className="tab__list direction--row" role="tablist">
{ childrenWithProps }
</ul>
</div>

控制台日志返回 componentDidMount 中的 ul html 元素。这也是预期的,因为组件已呈现。

但是,

当我测试这个组件时:

const children = <div> child </div>;

describe('Tab component', () => {
it('should render', () => {
const wrapper = mount(<Tab>{children}</Tab>);
const ulElement = wrapper.find('ul');
const instance = ulElement.instance().ref;
console.log('instance', instance);

expect(wrapper).toMatchSnapshot();
});
});

我的终端中的控制台日志语句(构造函数中的 this.myRef 和 componentDidMount 中)都显示 {current: null}instance 未定义。

任何人都可以帮我理解发生了什么事吗?谢谢!

最佳答案

我猜这仅在 React 16.3 或更高版本中受支持。并且应该安装 16.3 适配器!检查this下面复制了测试实现示例。

  class Foo extends React.Component {
constructor(props) {
super(props);
this.setRef = createRef();
}
render() {
return (
<div>
<div ref={this.setRef} className="foo" />
</div>
);
}
}

const wrapper = mount(<Foo />);
const element = wrapper.find('.foo').instance();
expect(wrapper.instance().setRef).to.have.property('current', element);

Looking at your code the following fix should probably work. You have to use the name of your ref, 'myRef', when accessing it from the instance.

//Component
export default class Tab extends React.Component {
constructor(props) {
super(props);
this.myRef = createRef();
}
componentDidMount() {
console.log("TAB Component Did Mount, REF is : ", this.myRef);
}

render() {
return (
<div className="tab_bar">
<ul
ref={this.myRef}
className="tab__list direction--row"
role="tablist"
>
<li>TEST</li>
</ul>
</div>
);
}
}

//Test
describe("Tab component", () => {
it("Ref should be available in instance", () => {
const wrapper = mount(<Tab />);
const ulElement = wrapper.find("ul");

expect(ulElement.instance()).not.toBeNull();
expect(wrapper.instance()).not.toBeNull();

expect(ulElement.instance()).toBe(wrapper.instance().myRef.current);
});
});

编辑:工作沙箱实例 https://codesandbox.io/s/enzyme-instance-3rktt

Make sure your Adapter version and the React version is the same

关于reactjs - React ref.current 仅在 Enzyme 测试中在 componentDidMount 中为 null,实时情况下不为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55292824/

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