[在React中使用Jest测试时如何调用ComponentDidMount

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

我有一个组件,其中ComponentDidMount试图调用API函数

componentDidMount(){

   this.getTypes(this.props.user).then(Response => {this.setState({List: Response.Types })});

  }

async getTypes(userLogin){
    try{
      res = await API.get(......... );
      } 
    catch(error) {
       ....
       }
}

现在我想调用componentDidMount和getTypes并模拟API.get。

因此,有人可以告诉我如何使用Jest调用componentDidMount和getTypes吗?

reactjs jest
1个回答
0
投票

使用Enzyme测试您的组件。

在测试中,将组件浅化为

shallow(<ComponentName {...props} />)

这将自动调用componentDidMount

现在模拟api调用,您可以使用nock甚至模拟整个Api.get方法,然后在测试中呈现组件。

© www.soinside.com 2019 - 2024. All rights reserved.