类型错误:使用 axios 编写单元测试时无法读取未定义的属性“get”

Ahm*_*qas 1 unit-testing reactjs jestjs enzyme axios

我正在为一个组件编写单元测试。我的组件有一个使用 axios 的方法。我想为它编写单元测试。这是我的写法,但出现错误。

import axios from "axios";
jest.mock('axios');
jest.mock('axios', () => ({ get: jest.fn(),post: jest.fn(), create: jest.fn() }));
test("on search it should call get store", () => {
    axios.get.mockImplementationOnce(() => Promise.resolve(data));
    const wrapper = shallow(<ComponentA />);
    const spy = jest.spyOn(wrapper.instance(), "getStores");
    wrapper.setState({
      searchText: "test1"
    });
    wrapper.instance().onSearchClick();
    expect(spy).toHaveBeenCalledWith("test1");
  });
Run Code Online (Sandbox Code Playgroud)

这是方法

getStores = term => {
    const uri = URI("")
      .path("/api/link")
      .addQuery({term: term})
      .toString();
    return axios.get(uri)
      .then(response => {
        const storeResponse = response.data;
          return storeResponse;
            } catch (error) {}
            this.props.onStoreFetch(stores, false);
          } else {
            this.props.onStoreFetch([], true);
          }
      })
      .catch(error => {
        this.props.onStoreFetch([], true);
      });
  };
Run Code Online (Sandbox Code Playgroud)

我得到的错误是

类型错误:无法读取未定义的属性“get”

sli*_*wp2 5

这是一个工作示例:

\n\n

index.tsx:

\n\n
import React, { Component } from \'react\';\nimport axios from \'axios\';\n\nclass SetStoreOverlay extends Component<any, any> {\n  constructor(props) {\n    super(props);\n    this.state = {\n      searchText: \'\',\n    };\n  }\n  getStores = (term) => {\n    const uri = `/searchux/api/v1/storeProxy?term=${term}`;\n\n    return axios\n      .get(uri)\n      .then((response) => console.log(response))\n      .catch((error) => {\n        this.props.onStoreFetch([], true);\n      });\n  };\n\n  onSearchClick = () => {\n    return this.getStores(this.state.searchText);\n  };\n\n  render() {\n    return <div></div>;\n  }\n}\n\nexport default SetStoreOverlay;\n
Run Code Online (Sandbox Code Playgroud)\n\n

index.spec.tsx:

\n\n
import React, { Component } from \'react\';\nimport SetStoreOverlay from \'./\';\nimport axios from \'axios\';\nimport { shallow } from \'enzyme\';\n\njest.mock(\'axios\', () => {\n  return {\n    get: jest.fn(),\n  };\n});\n\ndescribe(\'SetStoreOverlay\', () => {\n  afterEach(() => {\n    jest.resetAllMocks();\n  });\n  it(\'should pass\', async () => {\n    const data = {};\n    (axios.get as jest.Mocked<any>).mockImplementationOnce(() => Promise.resolve(data));\n    const mProps = { onStoreFetch: jest.fn() };\n    const wrapper = shallow(<SetStoreOverlay {...mProps} />);\n    const spy = jest.spyOn(wrapper.instance() as any, \'getStores\');\n    wrapper.setState({ searchText: \'test1\' });\n    wrapper.instance()[\'onSearchClick\']();\n    expect(spy).toHaveBeenCalledWith(\'test1\');\n    expect(axios.get).toBeCalledWith(`/searchux/api/v1/storeProxy?term=test1`);\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

带有覆盖率报告的单元测试结果:

\n\n
 PASS  src/stackoverflow/59317049/index.spec.tsx (14.204s)\n  SetStoreOverlay\n    \xe2\x9c\x93 should pass (27ms)\n\n  console.log src/stackoverflow/59317049/index.tsx:1599\n    {}\n\n-----------|----------|----------|----------|----------|-------------------|\nFile       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |\n-----------|----------|----------|----------|----------|-------------------|\nAll files  |    94.12 |      100 |    85.71 |    93.75 |                   |\n index.tsx |    94.12 |      100 |    85.71 |    93.75 |                18 |\n-----------|----------|----------|----------|----------|-------------------|\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        16.23s\n
Run Code Online (Sandbox Code Playgroud)\n\n

源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59317049

\n