From 889262c77cbbd7f88255cd837fe5ba70be68a1f7 Mon Sep 17 00:00:00 2001 From: Sunil Kumar Date: Mon, 7 Oct 2024 17:40:36 +0500 Subject: [PATCH] Added Unit Test for toErrorMessage utility --- .../unit/utils/to-error-message.test.ts | 37 +++++++++++++++++++ src/utils/to-error-message.tsx | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 src/__tests__/unit/utils/to-error-message.test.ts diff --git a/src/__tests__/unit/utils/to-error-message.test.ts b/src/__tests__/unit/utils/to-error-message.test.ts new file mode 100644 index 0000000..754d942 --- /dev/null +++ b/src/__tests__/unit/utils/to-error-message.test.ts @@ -0,0 +1,37 @@ +import { AxiosError } from "axios" +import { describe, expect, it } from "vitest" + +import { toErrorMessage } from "@/utils/to-error-message" + +describe("toErrorMessage", () => { + it("should return the error message from the response", () => { + const mockError = { + response: { + data: { + message: "Custom error message", + }, + }, + } as AxiosError + + const result = toErrorMessage(mockError) + expect(result).toBe("Custom error message") + }) + + it("should return default message if error message is not provided", () => { + const mockError = {} as AxiosError + + const result = toErrorMessage(mockError) + expect(result).toBe("Something went wrong, please try again") + }) + + it("should return default message if response or data is undefined", () => { + const mockError = { + response: { + data: undefined, + }, + } as AxiosError + + const result = toErrorMessage(mockError) + expect(result).toBe("Something went wrong, please try again") + }) +}) diff --git a/src/utils/to-error-message.tsx b/src/utils/to-error-message.tsx index 40deafd..ba68d51 100644 --- a/src/utils/to-error-message.tsx +++ b/src/utils/to-error-message.tsx @@ -2,6 +2,6 @@ import { AxiosError } from "axios" // eslint-disable-next-line @typescript-eslint/no-explicit-any export const toErrorMessage = (error: AxiosError) => { - const message = error.response?.data.message + const message = error.response?.data?.message return message || "Something went wrong, please try again" }