小编Ahm*_*qas的帖子

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

我正在为一个组件编写单元测试。我的组件有一个使用 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);
          } …
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs enzyme axios

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

axios ×1

enzyme ×1

jestjs ×1

reactjs ×1

unit-testing ×1