【问题标题】:Test componentWillUnmount() removes a class from body测试 componentWillUnmount() 从正文中删除一个类
【发布时间】:2017-01-04 20:32:24
【问题描述】:

我有以下代码的 React 组件:

  componentWillUnmount () {
    document.body.classList.remove('isPreloaded')
  }

我有 body 标签和 isPreloaded 类,预加载器 HTML 和最初在 index.html 中的样式(作为关键的东西)。加载应用程序时,Preloader 组件被渲染到正文中(对用户而言没有任何变化)。当数据从服务器到达时,Preloader 被删除。当然,我必须删除 isPreloaded 类,因为它会使正文无法滚动。

以上描述与我的问题没有直接关系,但我决定添加它以防止诸如“这是不好的做法”或类似的cmets。

所以我想测试这种行为。为了确保它按预期工作,我必须在 <body> 中使用类 isPreloaded 渲染这个组件并将它保存在一个变量中,让它成为 container。然后我必须检查这个类是否存在于container 中。在第二个测试中,我必须从容器中卸载组件并检查该类是否消失了。

这大约是我想要实现的目标:

describe('<Preloader />', () => {
  const container = mount(<body className='isPreloaded'><Preloader /></body>)

  it('should be rendered with `isPreloaded` class', () => {
    expect(container.find('isPreloaded').length).toBe(1)
  })

  ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(container).childNode)

  it('should remove `isPreloaded` class from body when unmounted', () => {
    expect(container.find('.isPreloaded').length).toBe(0)
  })
})

但它不起作用。第一个断言返回 0 而不是 1,因此失败。第二个抛出以下错误:

Invariant Violation: findDOMNode was called on an unmounted component.

【问题讨论】:

  • 反应版??
  • @Codesingh 15.4.1

标签: reactjs jestjs enzyme


【解决方案1】:

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(container).childNode) 是一个异步函数,所以你应该这样做:-

setTimeout(function() {
    ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(container).childNode)
}, 3000

您还可以将侦听器添加到 componentWillUnmount()。

对于it 问题使用这个:

let {TestUtils} = React.addons;
this.container = TestUtils.renderIntoDocument(<body       className='isPreloaded'><Preloader /></body>)
this.renderedDOM = () => React.findDOMNode(this.container);

it('should be rendered with `isPreloaded` class', () => {
    expect(this.renderedDOM().children.length).toEqual(1);
  })

【讨论】:

  • 也许使用setImmediate(或process.nextTick)一次或两次就足够了。 setImmediate(_ =&gt; setImmediate(func)) 将在调用后运行 func 两个主循环周期。到那时,回调可能已经运行了。无需等待 3 秒
  • 是的,这些都是替代品。
  • @Codesingh 感谢您的回答。你能提供完整的例子吗?另外,第一个返回 0 的 it 块呢?我该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多