我如何使用 Jest 酶为 componentDidMount 上的 API 调用编写测试用例

Tar*_*mar 5 reactjs jestjs enzyme

我想为 componentDidMount 上的 await API 调用编写一个测试用例,以获取成功和错误。

我添加了 API 调用的代码行为,请为此建议测试用例实现。

import {apiService} from './../../../_services'
import { Component } from 'react';


class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      contentId: 123,
      userID: 1345
    };
  }
  componentDidMount() {
    this.getMappedContent()
      .then(content => {
        if (content) {
          if (content.contentData && content.contentData.isLocked) {
            if (content.contentData.lockedByEmail !== this.state.userID) {
              this.setState({ isLocked, lockedBy })
            }
          }
          this.setState({users: content.contentData})
        }
      })
      .catch(error => {
      })
  }

  getMappedContent = async () => {
    if (!this.state.contentId) {
      return;
    }
    const requestParams = {
      contentId: this.state.contentId,
    };
    //getting existing mapContent item if exist
    return await apiService.getUser(requestParams);
  };
}
Run Code Online (Sandbox Code Playgroud)

// apiService.js 这里是我的API服务代码,请建议我写一个测试用例,成功失败

import Config from "./config";
import axiosInstance from "./axiosInstancs";

    const getUser = (params) => {
     const query = createQuery(params);
     const url = `${Config.users}${query ? query : ''}`
       return axiosInstance.get(url)
        .then(response => {
           return response.data.data;
         })
        .catch(error => {
          return false;
       });
    }
export const apiService = {
  getUser
}
Run Code Online (Sandbox Code Playgroud)

在这里,我试图编写一个成功和失败的测试用例,请建议我在这方面还能改进什么?

it('Should success API call with contentId', async () => {
        const expectedPosts = [
          {id: 1, title: 'test1'},
          {id: 2, title: 'test2'},
        ]
        const mock = jest.fn().mockReturnValue(expectedPosts);
        apiService.getUser = mock;
        const result = await apiService.getUser({contentId: 134});
        expect(result).toBe(expectedPosts);
     })

     it('Should not success API call without contentId', async () => {
        const expectedPosts = []
        const mock = jest.fn().mockReturnValue(expectedPosts);
        apiService.getUser = mock;
        const result = await apiService.getUser({});
        expect(result).toBe(expectedPosts);
     })
Run Code Online (Sandbox Code Playgroud)