间谍在componentDidMount中的方法调用

问题描述 投票:1回答:1

我想测试一些在React组件的componentDidMount生命周期方法中调用的自定义方法。

  componentDidMount() {
    getData().then(res => {
      console.log(res);
      this.setState({
        rate: res.data.bpi.USD.rate_float
      });
    });
  }

我从api.js导入getData方法:

export const getData = () => {
  return axios
    .get("https://api.coindesk.com/v1/bpi/currentprice.json")
    .then(res => {
      return res;
    });
};

使用Jest和Enzyme进行测试,如下所示:

describe("App", () => {
  describe("Calls getData when componentDidMount", () => {
    const spy = jest.spyOn(App.prototype, "getData");
    const wrapper = mount(<App {...props} />);
    wrapper.instance().getData();
    expect(spy).toHaveBeenCalled(1);
  });
});

它失败了:App › Calls getData when componentDidMount › encountered a declaration exception

并给我以下错误:

TypeError: Cannot read property '_isMockFunction' of undefined

我做错了什么?

javascript reactjs ecmascript-6 jestjs enzyme
1个回答
2
投票

getData不是App方法,它不能在App类上窥探,它在wrapper.instance()组件实例上不可用。

可以使用jest.mock模拟模块。适当的单元测试需要模拟除测试单元之外的所有内容。 axios请求可以用以下方式嘲笑:

import { getData } from '.../api';

jest.mock('.../api');

describe("App", () => {
  describe("Calls getData when componentDidMount", () => {
    getData.mockResolvedValue({ data: ... });
    const wrapper = mount(<App {...props} />);
    expect(getData).toHaveBeenCalled(1);
  });
});

请注意shallow enables lifecycle hooks by default,预计componentDidMount会在组件实例化时被调用。

getData可以通过嘲弄axios以类似的方式进行测试; this is shown in the manual

© www.soinside.com 2019 - 2024. All rights reserved.