状态改变后测试反应组件
Test react component after state changes
如何测试以下组件?
import React from "react";
class ModuleLoader extends React.Component {
state = {
Module: null
};
componentDidMount() {
this.props
.Module()
.then(loaded => {
this.setState({ Module: loaded.default });
})
}
render() {
if (this.state.error) {
return "error";
}
if (!this.state.Module) {
return "loading";
}
return <this.state.Module {...this.props} />;
}
}
export default ModuleLoader;
Prop 模块是 returns 承诺动态导入的函数。当该导入被解析并加载时 returns 一个反应组件,它应该存储在状态中并呈现。那么让组件解析网络请求加载它、显示它并在它呈现后检查断言的测试应该是什么样的?
我希望有一些东西可以检查渲染组件的状态是否发生了变化。但我不能在文档中资助类似的东西。
我正在使用 Meteor
、Mocha
和 Enzyme
。
如果无法使用 Enzyme
测试组件,我可以切换到替代方案。
谢谢。
为什么酶无法实现您想要的行为?您的 componentDidMount() 不会被浅层渲染调用吗?如果是这样,您可以尝试完全渲染 (https://github.com/airbnb/enzyme#full-dom-rendering),或者创建一个从 componentDidMount() 调用但也可以在单元测试中手动调用的辅助方法。然后等待该方法后,您可以测试渲染的组件是否包含 Module
。因此,我认为您有两种选择来测试此组件呈现 Module
.
解决方案是正确使用 promises 和 await
。
it('renders', async () => {
const props = {
Module: () =>
Promise.resolve({
default: () => <span>Im loaded!</span>,
}),
};
const component = mount(<ModuleLoader {...props} />);
expect(component).toMatchSnapshot();
await Promise.resolve(); // tick so promises resolve
expect(component.update()).toMatchSnapshot();
});
来源:https://gist.github.com/danielhusar/8df72f5677ec69cb9774c1d5c561c56a
如何测试以下组件?
import React from "react";
class ModuleLoader extends React.Component {
state = {
Module: null
};
componentDidMount() {
this.props
.Module()
.then(loaded => {
this.setState({ Module: loaded.default });
})
}
render() {
if (this.state.error) {
return "error";
}
if (!this.state.Module) {
return "loading";
}
return <this.state.Module {...this.props} />;
}
}
export default ModuleLoader;
Prop 模块是 returns 承诺动态导入的函数。当该导入被解析并加载时 returns 一个反应组件,它应该存储在状态中并呈现。那么让组件解析网络请求加载它、显示它并在它呈现后检查断言的测试应该是什么样的?
我希望有一些东西可以检查渲染组件的状态是否发生了变化。但我不能在文档中资助类似的东西。
我正在使用 Meteor
、Mocha
和 Enzyme
。
如果无法使用 Enzyme
测试组件,我可以切换到替代方案。
谢谢。
为什么酶无法实现您想要的行为?您的 componentDidMount() 不会被浅层渲染调用吗?如果是这样,您可以尝试完全渲染 (https://github.com/airbnb/enzyme#full-dom-rendering),或者创建一个从 componentDidMount() 调用但也可以在单元测试中手动调用的辅助方法。然后等待该方法后,您可以测试渲染的组件是否包含 Module
。因此,我认为您有两种选择来测试此组件呈现 Module
.
解决方案是正确使用 promises 和 await
。
it('renders', async () => {
const props = {
Module: () =>
Promise.resolve({
default: () => <span>Im loaded!</span>,
}),
};
const component = mount(<ModuleLoader {...props} />);
expect(component).toMatchSnapshot();
await Promise.resolve(); // tick so promises resolve
expect(component.update()).toMatchSnapshot();
});
来源:https://gist.github.com/danielhusar/8df72f5677ec69cb9774c1d5c561c56a