首页 > 解决方案 > 如何用 Jest 测试 catch 函数

问题描述

如何从这样的函数中测试捕获:

getApi () {
    const URL = '/api/division?key='
    axios.get(URL)
      .then((response) => {
        this.counter = response.data
      })
      .catch(err => {
        alert(err)
      })
  }

我正在使用 axios 和 vue js 来测试 JEST。希望有任何解决方案,谢谢:')

标签: vue.jsmockingaxiosjestjs

解决方案


Try axios-mock-adapter,它可以模拟axios.get()调用的结果,允许您模拟特定请求的网络错误/超时(从而catch在代码中调用回调):

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

const mock = new MockAdapter(axios);
mock.onGet(`/* URL used by component */`).networkError();

示例单元测试getApi()

it("does not modify username from network error", async () => {
  mock.onGet(`/* URL used by component */`).networkError();
  await wrapper.vm.getApi();
  expect(wrapper.vm.username).toBe(INIT_USERNAME);
});

it("does not modify username from network timeout", async () => {
  mock.onGet(`/* URL used by component */`).timeout();
  await wrapper.vm.getApi();
  expect(wrapper.vm.username).toBe(INIT_USERNAME);
});

演示


推荐阅读