如何为ES6类React组件创建Chai/Mocha单元测试?
问题描述:
我在为ES6类创建Chai/Mocha单元测试时遇到了麻烦。这个项目配置正确,使用chai/mocha,ES6,babel,所以这不是问题。 (我可以运行一个虚拟测试,检查两个变量是否相同)。仅当我尝试使用下面的ES6类React组件时,才会引发该错误。我使用命令npm test运行测试。我的package.json配置为运行该命令时,我跑NPM测试:如何为ES6类React组件创建Chai/Mocha单元测试?
mocha --compilers js:babel/register file/path/to/spec --recursive
我收到此错误:
警告:的setState(...):只能更新一安装或安装部件。这通常意味着您在卸载的组件上调用了setState()。这是一个没有操作。请检查代码组件
的ES6类阵营组成,看起来像(显然不是全部的话):
import ...
class Car extends React.Component {
constructor() {
super();
this.state = {
color: ''
}
}
setColor(color) {
this.setState({ color : color });
}
render() {
.......
}
}
测试/规格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
});
});
答
我的想法是调用new Car()只是调用构造函数而不是渲染方法,这意味着组件不会启动安装(请参阅生命周期文档https://facebook.github.io/react/docs/component-specs.html)。所以警告的意思是“嘿,你的组件没有开始安装,你怎么想setState,它有什么问题”。
如果你都OK使用TestUtils,你可以像
var car = TestUtils.renderIntoDocument(
<Car />
);
答
所有问题首先看起来更具体到你的组件,所以没有张贴至少你的渲染方法并不多,可以说。
否则速战速决将是检查你的组件是否安装或没有,像这样:
componentWillUnmount() {
this.isUnmounted = true;
}
setColor(color) {
if (!this.isUnmounted) {
this.setState({ color : color });
}
}
其他解决方案可以使用尝试捕捉:
setColor(color) {
try {
this.setState({ color : color });
return true;
} catch (e) {
return false;
}
}