【问题标题】:How do I setup correct testing for axios in React?如何在 React 中为 axios 设置正确的测试?
【发布时间】:2021-05-05 21:23:47
【问题描述】:

我在 React 中使用 axios,但在测试时遇到问题

这是我迄今为止在我的 test.js 文件中尝试过的:

jest.mock('axios');

describe('RssFeed', () => {
  let component;
  let data;

  beforeEach( () => {
    data = data {
      data: {...}
    };
  }

  test('fetches data successfully', (done) => {
    axios.get.mockResolvedValue(data);
    setTimeout(() => {
      expect(axios).toHaveBeenCalled();
      done();
    }, 500);
  });
});

这就是我在组件中设置 axios.get 的方式:

const [feedBody, setFeedBody] = useState([]);
const apiUrl = 'apiUrl';

useEffect( () => {
  axios.get(apiUrl)
       .then((response) => (response.data))
       .then((data) => {
         setFeedBody(data);
       })
       .catch((err) => console.log(err));
}, []);

运行测试后,我得到:

错误:未捕获 [错误:expect(jest.fn()).toHaveBeenCalled() 预期调用次数:>= 1 接听电话数:0]

提前致谢

【问题讨论】:

标签: reactjs jestjs axios enzyme


【解决方案1】:

我建议使用axios-mock-adapter,非常方便:

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const mock = new MockAdapter(axios);
const resp = 'success';
const testInput = 'testInput';
mock.onGet().reply(200, resp);

// expect feedBody to be 'success'

mock.reset();

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 2022-07-06
    • 2018-01-23
    • 2020-11-11
    • 2021-05-29
    • 1970-01-01
    • 2021-11-29
    • 2020-10-21
    • 2017-06-12
    相关资源
    最近更新 更多