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" }