为什么我收到: TypeError: _axios.default.get.mockResolvedValue is not a function

Bla*_*ere 4 reactjs jestjs axios

这是错误:

    TypeError: _axios.default.get.mockResolvedValue is not a function

      20 |         ]
      21 |     }
    > 22 |     Axios.get.mockResolvedValue(response);
         |               ^
      23 | 
      24 |     const component = renderer.create(
      25 |         <BookList />
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

import React from "react";
import Axios from "axios";
import {shallow, mount, render} from "enzyme";

import BookList from "../BookList";

import renderer from "react-test-renderer";

jest.mock('Axios');

test("<BookList /> snapshot test", () => {
    const response = {
        data: [
            {
                title: "foo"
            },
            {
                title: "bar"
            }
        ]
    }
    Axios.get.mockResolvedValue(response);

    const component = renderer.create(
        <BookList />
    )
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
})
Run Code Online (Sandbox Code Playgroud)

小智 8

您收到此错误是因为mockResolvedValue中不存在Axios.post。您必须根据需要输入大小写

(Axios.get as jest.Mock<{}>).mockResolvedValue(response);
Run Code Online (Sandbox Code Playgroud)

另外,请确保根据需要初始化 Axios.get 的值。喜欢

Axios.get = jest.fn()
Run Code Online (Sandbox Code Playgroud)

jest.mock('Axios');
Run Code Online (Sandbox Code Playgroud)

必须是

jest.mock('axios');
Run Code Online (Sandbox Code Playgroud)

  • @BlaineLafreniere 我遇到了同样的问题,但对我来说, jest.mock('axios') 在我的describe() 语句中。一旦我把它放在外面,我就能够访问mockResolvedValue()函数。我认为您的问题只是导入时 axios 的大写。 (2认同)