在componentDidMount内部模拟API调用方法

问题描述 投票:1回答:1

有人对如何对该组件进行单元测试有任何建议吗?我正在努力研究如何正确模拟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个回答
0
投票

我将使用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); 
});
© www.soinside.com 2019 - 2024. All rights reserved.