假设我有这个简单的React组件:
class Greeting extends React.Component {
constructor() {
fetch("https://api.domain.com/getName")
.then((response) => {
return response.text();
})
.then((name) => {
this.setState({
name: name
});
})
.catch(() => {
this.setState({
name: "<unknown>"
});
});
}
render() {
return <h1>Hello, {this.state.name}</h1>;
}
}
根据以下答案和更多的研究,我得出了一个最终方案来测试resolve()
情况:
test.only("greeting name is 'John Doe'", async () => {
const fetchPromise = Promise.resolve({
text: () => Promise.resolve("John Doe")
});
global.fetch = () => fetchPromise;
const app = await shallow(<Application />);
expect(app.state("name")).toEqual("John Doe");
});
目前代码的运行很好。我的问题是如何测试catch()
语句。以下代码并没有按照我预期地运行:
test.only("greeting name is 'John Doe'", async () => {
const fetchPromise = Promise.reject(undefined);
global.fetch = () => fetchPromise;
const app = await shallow(<Application />);
expect(app.state("name")).toEqual("<unknown>");
});
断言失败,
name
为空:expect(received).toEqual(expected)
Expected value to equal:
"<unknown>"
Received:
""
at tests/components/Application.spec.tsx:51:53
at process._tickCallback (internal/process/next_tick.js:103:7)
我错过了什么?
componentDidMount
的人。React文档推荐使用这个生命周期回调来实例化网络请求。但除了测试和我的特定问题之外,是否在构造函数中进行网络请求是一种不好的做法?如果是,为什么? - rfgamaral