如何用Jest测试catch功能

时间:2018-07-27 07:49:26

标签: vue.js mocking axios jestjs

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

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

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

1 个答案:

答案 0 :(得分:1)

尝试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);
});

demo