无法读取未定义的 属性 'then' - Axios 进入 React

Cannot read property 'then' of undefined - Axios get in React

我想模拟点击一个按钮(#reset),按钮有 onClick 用 axios 抓取。我想模拟此数据,但出现错误:“无法读取未定义的 属性 'then'”

测试:

import React from "react";
import PersonsList from "./Components/PersonsList/PersonsList";
import * as axios from "axios";
import { shallow } from "enzyme";

const mockData = [
  {
    gender: "female",
  },
];
jest.mock("axios");
describe("axios", () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<PersonsList />);
  });
  axios.get.mockResolvedValue({ data: mockData });
  it("reset", () => {
    const resetButton = wrapper.find("#reset");
    resetButton.simulate("click");
  });
});

按钮:

  <button
          className="actions__modify-list"
          onClick={() => {
            getPeople();
          }}
          id="reset"
        >

单击按钮时调用的函数:

  const getPeople = () => {
    const url = "https://randomuser.me/api/?results=10";
    axios(url)
      .then((res) => {
        setPeople(res.data.results);
      })
      .catch(() => {
        setError(true);
      });
  };

您应该模拟 axios()NOT axios.get() 方法的解析值。

例如

PersonsList.jsx:

import axios from 'axios';
import React, { useState } from 'react';

export function PersonsList() {
  const [person, setPeople] = useState();
  const [error, setError] = useState(false);

  const getPeople = () => {
    const url = 'https://randomuser.me/api/?results=10';
    axios(url)
      .then((res) => {
        setPeople(res.data.results);
      })
      .catch(() => {
        setError(true);
      });
  };

  return (
    <div>
      <button
        className="actions__modify-list"
        onClick={() => {
          getPeople();
        }}
        id="reset"
      ></button>
    </div>
  );
}

PersonsList.test.jsx:

import { PersonsList } from './PersonsList';
import axios from 'axios';
import React from 'react';
import { shallow } from 'enzyme';

jest.mock('axios');

const mockData = [{ gender: 'female' }];

describe('68393613', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<PersonsList />);
  });
  test('should pass', () => {
    axios.mockResolvedValue({ data: mockData });
    const resetButton = wrapper.find('#reset');
    resetButton.simulate('click');
  });
});

测试结果:

 PASS  examples/68393613/PersonsList.test.jsx (8.311 s)
  68393613
    ✓ should pass (12 ms)

-----------------|---------|----------|---------|---------|-------------------
File             | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------------|---------|----------|---------|---------|-------------------
All files        |   91.67 |      100 |      80 |   91.67 |                   
 PersonsList.jsx |   91.67 |      100 |      80 |   91.67 | 15                
-----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.837 s, estimated 11 s