首页 > 解决方案 > React ref.current 在 componentDidMount 中仅在酶测试中为空,而不是实时为空

问题描述

我对测试 React 组件相当陌生,并且正在努力测试使用 React.createRef 创建的 ref。我已经阅读了这个很棒的回复,不确定它是否解决了我的问题。在 ref 回调之前调用 componentDidMount

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 中的ulhtml 元素。这也是预期的,因为组件已渲染。

然而,

当我测试这个组件时:

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();
  });
});

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

谁能帮我理解发生了什么?谢谢!

标签: reactjsunit-testingenzyme

解决方案


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

  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);

查看您的代码,以下修复可能会起作用。从实例访问它时,您必须使用您的 ref 的名称“myRef”。

//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);
  });
});

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

确保您的Adapter 版本React 版本相同


推荐阅读