首页 > 解决方案 > 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;

标签: reactjsjestjsenzyme

解决方案


推荐阅读