【问题标题】:Mocking an API call method inside componentDidMount在 componentDidMount 中模拟 API 调用方法
【发布时间】:2020-03-06 13:26:43
【问题描述】:

有人对如何对这个组件进行单元测试有任何建议吗?我正在努力弄清楚如何正确地模拟 getFoo,然后在运行我的测试之前等待它的承诺得到解决。我目前正在使用 Jest 来尝试这样做。

import { getFoo } from "../../../api/fooApi";

class Accordion extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isActive: false,
      isLoaded: false
    };
  }

  componentDidMount() {
    getFoo(this.props.id).then(
      result => {
        this.setState({
          isLoaded: true,
          foo: result
        });
      },
      error => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    );
  }

  render() {
    const { isActive, isLoaded, foo } = this.state;

    if (!isLoaded) return <Spinner />;

    return (
      <Accordion styled>
        <Accordion.Title
          active={isActive}
          onClick={() => {
            this.setState({ isActive: !isActive });
          }}
        >
          <Icon name="dropdown" />
          {foo}
        </Accordion.Title>
        <Accordion.Content active={isActive}>
          {foo}
        </Accordion.Content>
      </Accordion>
    );
  }
}

这是实际的方法。

export async function getFoo(id) {
  const res = await fetch(`/api/foo/${id}`);
  if (res.status !== 200) throw Error;
  return res.json();
}

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    我会使用nock,它可以让您模拟 API 响应,here's a post detailing how to use it,它会类似于以下内容:

    ...
    import nock from 'nock'; 
    
    it('renders without crashing', () => { 
    
       const scope = nock('http://myapi.com') 
       .get('/api/foo/')
       .reply(200, { products: [{ id: 1, name: 'nocked data' }] }, 
       { 
         'Access-Control-Allow-Origin': '*', 
         'Content-type': 'application/json' 
       }); 
    
       const div = document.createElement('div');
       ReactDOM.render(<ProductsList />, div);
       ReactDOM.unmountComponentAtNode(div); 
    });
    

    【讨论】:

      猜你喜欢
      • 2019-03-18
      • 2021-01-29
      • 2018-10-25
      • 1970-01-01
      • 2015-08-23
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多