Reactjs componentWillMount()的React JS测试用例,异步测试API调用

Reactjs componentWillMount()的React JS测试用例,异步测试API调用,reactjs,testing,tdd,Reactjs,Testing,Tdd,我正在为下面的代码编写一个测试用例 export default class App extends React.Component { constructor(props) { super(props); this.state = { userProfile: {} }; } async componentWillMount() { const res = await fetch('/api/getUserDetails'); console.log

我正在为下面的代码编写一个测试用例

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { userProfile: {} };
  }
  async componentWillMount() {
    const res = await fetch('/api/getUserDetails');
    console.log('App.jsx: RES- Result: ', res);
    let userProfile = await res.json();

    console.log('App.jsx: userProfile- Result: ', userProfile);

    userProfile = mapApiObjectToModel(userProfile);

    this.setState({ userProfile });
  }
}
mapApiObjectToModel:

import React from 'react';

export const mapApiObjectToModel = inputObj => {
  const outputObj = {};
  const authorizedRoles = ['Admin'];

  if (inputObj) {
    outputObj.fullName = '';

    if (inputObj.data) {
      outputObj.fullName = inputObj.data.data;
    }

    outputObj.role = 'Admin';
    outputObj.isAuthorized = authorizedRoles.includes(outputObj.role);
  }
  console.log('outputObj', outputObj);
  return outputObj;
};
res: 决议:正文:(……) bodyUsed:对 标题:标题{} 好的,没错 重定向:错误 现状:200 状态文本:“ 类型:“基本” url:“http://localhost:7000/api/getUserDetails" 原型:响应

用户配置文件:

数据:{firstName:“Admin”,groupName:“ROLE_Admin”} 状态:“成功” 原型:对象

我从互联网上尝试了多种方法,但似乎没有任何效果。因此我没有发布我写的代码


非常感谢您的帮助:)

您使用的是什么测试框架?您正在寻找单元测试、集成测试或e2e测试吗?请尝试更改
this.setState({userProfile})
to
this.setState({…userProfile})
或者您可以使用
this.setState({userProfile:userProfile})-查看这是否适用于您。