6

当我从 React 12.2 升级到 React 13.3 时,我的测试套件中出现以下错误:

错误:不变违规:unmountComponentAtNode(...):目标容器不是 DOM 元素。

我正在使用这篇博客文章来使用 Jasmine 测试我的代码。此代码中出现错误:

describe("A component", function() {

  var instance;
  var container = document.createElement("div");

  afterEach(function() {
    if (instance && instance.isMounted()) {
      // Only components with a parent will be unmounted
      React.unmountComponentAtNode(instance.getDOMNode().parent);
    }
  });
  ...rest of test suite...
  // the instances of renderIntoDocument that cause the failure look like the below
  it("Causes my test suite to fail.", function() {
    instance = TestUtils.renderIntoDocument(<MyReactElement/>);
  });
)};

我知道这getDOMNode()已被弃用,但这不是导致错误的原因。

当我检查instance.getDOMNode()它时,它返回给定的实例,但是当它出错时,它instance.getDOMNode().parent是未定义的。调用React.unmountComponentAtNode这个未定义的变量会导致错误。

像这样的答案表明存在某种竞争条件,但我不确定这将如何应用于我的测试套件。谢谢你的帮助!

4

1 回答 1

6

解决方法是改变:

React.unmountComponentAtNode(instance.getDOMNode().parent);

至:

React.unmountComponentAtNode(instance.getDOMNode().parentNode);

或者,如果您要从 移动getDOMNode()findDOMNode()

React.unmountComponentAtNode(React.findDOMNode(instance).parentNode);
于 2015-06-27T15:39:32.627 回答