reactjs - ReactJS componentDidMount 获取单元测试
问题描述
我刚刚开始学习 React,我正在尝试执行一些测试来绕过它。
我正在使用 API,而我的 componentDidMount 使用 feth 调用。执行componentDidMount或创建组件时如何模拟从fetch返回数据?基本上我只想模拟假呼叫,然后检查状态是否填充了这些数据。 我知道在测试 Angular 组件时使用 Jasmine 可以执行类似 spyOn().thenReturn() 之类的操作,我该如何实现呢?
这是代码:
import React from 'react';
import './App.css';
import { CardList } from './components/card-list/card-list.component';
import { Search } from './components/search/search.component';
class App extends React.Component {
constructor() {
super();
this.state = {
pokemons: [],
searchField: ''
}
}
componentDidMount() {
fetch('http://pokeapi.co/api/v2/pokemon/?limit=10')
.then(res => res.json())
.then(res =>
Promise.all(
res.results.map(
element => fetch(element.url)
.then(res => res.json())
.then(pokemon => { return { id: pokemon.id, name: pokemon.name, img: pokemon.sprites.front_default } })
)
)
).then(pokemons => this.setState({ pokemons }));
}
render() {
return (
<div className="App">
<CardList pokemons={this.state.pokemons} />
</div>
);
}
}
export default App;
解决方案
推荐阅读
- angular - 如何将 Angular 8 http 请求返回值保存在变量中?
- ios - 分享 pdf 文件 .Swift
- python - 无法连接到 Browsermob-proxy ProxyServerError
- r - 在 R 中使用 dplyr 汇总函数时不显示小数位
- c - 行内汇编方法使整个程序崩溃
- html - 如何在 tumblr HTML 编辑器 [2019] 上添加段落而不会出错?
- c++ - 将 c++ 类更改为模板
- typescript - 我可以显式导入 dom 类型吗?
- swift - SwiftUI:FetchedResults 的 ForEach 给出错误 - “'NSManagedObject' 类型的值没有成员......”
- google-apps-script - 任何想法都是为什么这个 Google App Script 过滤器不能正确过滤