OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to write jest test case for the catch block in axios() method

  • Thread starter Thread starter user2613946
  • Start date Start date
U

user2613946

Guest
I am new to this unit testing. I am getting an error in jet unit testing. Below is my code.

index.ts:

Code:
export const getData = async (): Promise<any> => {
  const url = `/dataHistory`;
  return new Promise((resolve, reject) => {
    axios({
      method: "get",
      url: url
    })
      ?.then((res) => {
        resolve(res?.data);
      })
      ?.catch((err) => {
        reject(err?.response?.data?.message);
      });
  });
};

index.test.ts:

Code:
import { getData } from "./index";
const axios = require('axios');
jest.mock('axios');

describe("getData Services", () => {
  it("should call getData",async () => {
    let errMsg = new Error();
    axios.mockImplementationOnce(() => Promise.reject(errMsg));
    const result =  await getData(mockRequest);
    expect(result).rejects.toThrow(errMsg);
  });
});

Not able to crack what I am missing in this syntax. Can you help me in resolving this?

<p>I am new to this unit testing. I am getting an error in jet unit testing. Below is my code.</p>
<p><strong>index.ts:</strong></p>
<pre><code>export const getData = async (): Promise<any> => {
const url = `/dataHistory`;
return new Promise((resolve, reject) => {
axios({
method: "get",
url: url
})
?.then((res) => {
resolve(res?.data);
})
?.catch((err) => {
reject(err?.response?.data?.message);
});
});
};
</code></pre>
<p><strong>index.test.ts:</strong></p>
<pre><code>import { getData } from "./index";
const axios = require('axios');
jest.mock('axios');

describe("getData Services", () => {
it("should call getData",async () => {
let errMsg = new Error();
axios.mockImplementationOnce(() => Promise.reject(errMsg));
const result = await getData(mockRequest);
expect(result).rejects.toThrow(errMsg);
});
});
</code></pre>
<p>Not able to crack what I am missing in this syntax. Can you help me in resolving this?</p>
 
Top