3

我有一个使用 React 作为视图层的项目。为了测试它,我使用了 mocha、karma、karma-webpack 等。出于某种原因,在 React 16+ 中,karma 报告afterEach说 已经为两个规范运行了 3 次。这在 React 16+ 中发生,并且process.env.NODE_ENVisdevelopmentnot production时发生。

在之前对该问题的探索中,规范失败的原因可能会级联并污染后续规范。为了帮助确定根本原因,这是我能找到的最简单的例子。

我试图追踪这种行为,但被业力和套接字内部和周围的复杂性所困扰。考虑下面的示例,目前可在https://github.com/jneander/react-mocha获得。

Example.js

import React, {Component} from 'react'

export default class Example extends Component {
  render() {
    try {
      return (
        <div>{this.props.foo.bar}</div>
      )
    } catch(e) {
      console.log(e) // for logging purposes
      throw e
    }
  }
}

Example.spec.js

import {expect} from 'chai'
import React from 'react'
import ReactDOM from 'react-dom'

class ExampleWrapper extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      error: false
    }
  }

  componentDidCatch(error) {
    console.log('there was a problem')
    this.setState({
      error: true
    })
  }

  render() {
    console.log('rendering!')
    if (this.state.error) {
      console.log('- rendering the error version')
      return <div>An error occurred during render</div>
    }

    console.log('- rendering the real version')
    return (
      <Example {...this.props} />
    )
  }
}

import Example from './Example'

describe('Example', () => {
  let $container

  beforeEach(() => {
    console.log('beforeEach')
    $container = document.createElement('div')
    document.body.appendChild($container)
  })

  afterEach(() => {
    console.log('afterEach')
    ReactDOM.unmountComponentAtNode($container)
    $container.remove()
  })

  async function mount(props) {
    return new Promise((resolve, reject) => {
      const done = () => {
        console.log('done rendering')
        resolve()
      }
      ReactDOM.render(<ExampleWrapper {...props} />, $container, done)
    })
  }

  it('fails this spec', async () => {
    console.log('start test 1')
    await mount({})
    expect(true).to.be.true
  })

  it('also fails, but because of the first spec', async () => {
    console.log('start test 2')
    await mount({foo: {}})
    expect(true).to.be.true
  })
})

规格输出如下:

LOG LOG: 'beforeEach'
LOG LOG: 'start test 1'
LOG LOG: 'rendering!'
LOG LOG: '- rendering the real version'

  Example
    ✗ fails this spec
  Error: Uncaught TypeError: Cannot read property 'bar' of undefined (src/Example.spec.js:35380)
      at Object.invokeGuardedCallbackDev (src/Example.spec.js:16547:16)
      at invokeGuardedCallback (src/Example.spec.js:16600:31)
      at replayUnitOfWork (src/Example.spec.js:31930:5)
      at renderRoot (src/Example.spec.js:32733:11)
      at performWorkOnRoot (src/Example.spec.js:33572:7)
      at performWork (src/Example.spec.js:33480:7)
      at performSyncWork (src/Example.spec.js:33452:3)
      at requestWork (src/Example.spec.js:33340:5)
      at scheduleWork (src/Example.spec.js:33134:5)

ERROR LOG: 'The above error occurred in the <Example> component:
    in Example (created by ExampleWrapper)
    in ExampleWrapper

React will try to recreate this component tree from scratch using the error boundary you provided, ExampleWrapper.'
LOG LOG: 'there was a problem'
LOG LOG: 'done rendering'
LOG LOG: 'rendering!'
LOG LOG: '- rendering the error version'
LOG LOG: 'afterEach'
LOG LOG: 'beforeEach'
LOG LOG: 'start test 2'
LOG LOG: 'rendering!'
LOG LOG: '- rendering the real version'
LOG LOG: 'done rendering'
    ✓ also fails, but because of the first spec
    ✓ also fails, but because of the first spec
LOG LOG: 'afterEach'
LOG LOG: 'afterEach'

Chrome 69.0.3497 (Mac OS X 10.13.6): Executed 3 of 2 (1 FAILED) (0.014 secs / NaN secs)
TOTAL: 1 FAILED, 2 SUCCESS


1) fails this spec
     Example
     Error: Uncaught TypeError: Cannot read property 'bar' of undefined (src/Example.spec.js:35380)
    at Object.invokeGuardedCallbackDev (src/Example.spec.js:16547:16)
    at invokeGuardedCallback (src/Example.spec.js:16600:31)
    at replayUnitOfWork (src/Example.spec.js:31930:5)
    at renderRoot (src/Example.spec.js:32733:11)
    at performWorkOnRoot (src/Example.spec.js:33572:7)
    at performWork (src/Example.spec.js:33480:7)
    at performSyncWork (src/Example.spec.js:33452:3)
    at requestWork (src/Example.spec.js:33340:5)
    at scheduleWork (src/Example.spec.js:33134:5)

是什么导致重复报告?

为什么这发生在 React 16+ 而不是 React 15?

我该如何解决这个问题?

4

2 回答 2

0

似乎 React 16+ 在渲染过程中会出现未捕获的错误,即使componentDidCatch在包装器中使用也是如此。这意味着 Mocha 将因未捕获的错误而使测试失败,然后继续下一个测试,之后组件的第二次渲染将完成并解决 promise,运行一个断言。这在当前正在进行的测试中运行,导致在此示例中看到双重成功。

Github 上的 React repo 已经打开了一个问题。

于 2018-09-18T17:51:50.343 回答
0

可能存在竞争条件,因为 promise 是用ref函数解决的。已收到组件 ref 并不意味着初始渲染已完成。

正如参考文献所述,

如果您需要对根 ReactComponent 实例的引用,首选的解决方案是将回调 ref 附加到根元素。

解决承诺的正确方法是使用render回调参数,

如果提供了可选的回调,它将在组件渲染或更新后执行。

它应该是:

async function mount(props) {
  return new Promise(resolve => {
    ReactDOM.render(<Example {...props} />, $container, resolve)
  })
}

该问题不会出现在第二次测试中,它发生在第一次测试中,无论是否有第二次测试,并且不是特定于 React 16.5。它特定于 React 开发模式的工作方式

这是一个不包括 Mocha 因素的简化演示。输出了预期的错误,但是React 本身正在输出console.warn两个Error: Cannot read property 'bar' of undefined错误。运行组件函数两次,并从第一次测试异步输出错误。console.errorReactDOM.renderrender

与 React 的生产构建相同的演示同步显示了一个Error: Cannot read property 'bar' of undefined错误,正如预期的那样。失败的渲染不会使ReactDOM渲染拒绝,如果需要,错误边界组件可以捕获错误

class EB extends Component {
  componentDidCatch(err) {
    this.props.onCatch(err);
  }

  render() {
    return this.props.children;
  }
}

async function mount(props) {
  return new Promise((resolve, reject) => {
    ReactDOM.render(<EB onCatch={reject}><Example {...props} /></EB>, $container, resolve)
  })
}

在单元测试中不依赖 React DOM 渲染器是一个好习惯。Enzyme 服务于这个目的,并允许独立地同步测试组件,特别是shallow包装器

于 2018-09-07T16:32:16.080 回答