【发布时间】:2019-01-18 19:16:52
【问题描述】:
我有以下 React 组件,它在 componentDidMount() 上执行异步操作,一旦接收到数据,就会使用结果更新状态。
import * as React from "react";
export interface IAppProp {
App: any
}
export interface IAppProp {
App: any
}
export class App extends React.Component<IAppProp, IAppState> {
constructor(props: IAppProp) {
super(props);
this.state = { App: undefined };
}
public componentDidMount(){
// Some async operation
// Once data comes in update state as follows
this.setState({ App: data returned from async operation });
}
public render() {
if (this.state && this.state.App) {
return (
<SomeComponent />
)
} else {
return <span>Loading...</span>
}
}
}
但是,当我等待数据返回时,我在 render() 函数中返回了 Loading... 消息。
我正在尝试在我的 Jest 测试中测试此 Loading 状态。这是我目前所拥有的:
it("Should display loading when state is undefined", () => {
const inputControl = enzyme.mount(<MyApp App={pass in the right prop} />);
expect(inputControl.find("span").text()).toEqual("Loading...");
});
我知道上面的内容是错误的,因为它永远找不到加载中的span。我还尝试在 props 中传递 undefined,但这会使测试崩溃,因为 componentDidMount() 中的异步操作需要一个合法的 prop。
我该如何测试呢?谢谢!
【问题讨论】:
-
您应该能够通过mocking 测试中的异步操作或/和将
async添加到您的测试中来测试它。能否提供componentDidMount的完整代码?