如何为 ES6 class React 组件创建 Chai/Mocha 单元测试?

How to create Chai/Mocha unit tests for a ES6 class React component?

我在为 ES6 class 创建 Chai/Mocha 单元测试时遇到问题。该项目已正确配置为使用 chai/mocha、ES6、babel,所以这不是问题所在。 (我可以 运行 一个虚拟测试,我检查 2 个变量是否相同)。只有当我尝试使用下面的 ES6 class React 组件时才会抛出错误。我 运行 使用命令 npm test 进行测试。当我 运行 npm test:

时,我的 package.json 配置为 运行 这个命令
mocha --compilers js:babel/register file/path/to/spec --recursive

我收到此错误:

警告:setState(...):只能更新已安装或安装的组件。这通常意味着您在未安装的组件上调用了 setState() 。这是一个空操作。请检查组件代码

ES6 class React 组件看起来像(显然不是全部):

import ...

class Car extends React.Component {
  constructor() {
    super();
    this.state = {
      color: ''
    }
  }

  setColor(color) {
     this.setState({ color : color });
  }

  render() {
    .......
  }
}

test/spec JS 文件看起来(大部分像):

import ...

let should = chai.should();
describe('Car Test', () => {
  let car;

  beforeEach(() => {
    car = new Car();
  });

  it('should be red', () => {
    car.setColor('red'); // pretty sure THIS is throwing the error
  });
});

首先,问题看起来更具体到您的组件,所以如果不发布至少您的渲染方法,就没什么可说的了。

否则,快速解决方法是检查您的组件是否已安装,如下所示:

componentWillUnmount() {
   this.isUnmounted = true;
}

setColor(color) {
   if (!this.isUnmounted) {
      this.setState({ color : color });
   }
}

其他解决方案可以是使用 try catch:

setColor(color) {
   try {
    this.setState({ color : color });
    return true;
  } catch (e) {
    return false;
  }
}

我的想法是调用 new Car() 只是调用构造函数而不是 render 方法,这意味着组件不会开始挂载(参见生命周期文档 https://facebook.github.io/react/docs/component-specs.html)。所以警告意味着 "Hey, your component did not start mounting, how come you want to setState, it has something wrong".

如果您可以使用 TestUtils,您可以使用

var car = TestUtils.renderIntoDocument(
   <Car />
);