yoppie97
yoppie97

Reputation: 177

How to test catch function with Jest

How to test catch from function like this:

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

I'm using axios and vue js with testing JEST. Hope any solution, thanks :')

Upvotes: 3

Views: 1811

Answers (1)

tony19
tony19

Reputation: 138656

Try axios-mock-adapter, which can mock the results of axios.get() calls, allowing you to simulate a network error/timeout for a specific request (thus invoking the catch callback in your code):

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

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

Example unit tests for 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

Upvotes: 1

Related Questions