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

ASG*_*ASG 6 unit-testing reactjs enzyme

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

constructor(props) {
    super(props);
    this.myRef = React.createRef();
    console.log('this.myRef in constructor', this.myRef);
}
Run Code Online (Sandbox Code Playgroud)

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

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

控制台日志返回ulcomponentDidMount中的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();
  });
});
Run Code Online (Sandbox Code Playgroud)

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

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

Deh*_*oos 2

我猜这仅在 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);
Run Code Online (Sandbox Code Playgroud)

查看您的代码,以下修复可能应该有效。从实例访问它时,您必须使用引用的名称“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);
  });
});
Run Code Online (Sandbox Code Playgroud)

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

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