Переглянути джерело

test: add tests for handle-server-error

satnaing 2 місяців тому
батько
коміт
f5cc03a0c9
3 змінених файлів з 46 додано та 2 видалено
  1. 41 0
      src/lib/handle-server-error.test.ts
  2. 4 2
      src/lib/handle-server-error.ts
  3. 1 0
      vite.config.ts

+ 41 - 0
src/lib/handle-server-error.test.ts

@@ -0,0 +1,41 @@
+import { AxiosError } from 'axios'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { handleServerError } from './handle-server-error'
+
+const toastError = vi.hoisted(() => vi.fn())
+
+vi.mock('sonner', () => ({
+  toast: {
+    error: toastError,
+  },
+}))
+
+beforeEach(() => {
+  vi.mocked(toastError).mockClear()
+})
+
+describe('handleServerError', () => {
+  it('shows a generic message when the error is not recognised', () => {
+    handleServerError(new Error('network'))
+
+    expect(toastError).toHaveBeenCalledWith('Something went wrong!')
+  })
+
+  it('shows a not-found style message for a 204 status payload', () => {
+    handleServerError({ status: 204 })
+
+    expect(toastError).toHaveBeenCalledWith('Content not found.')
+  })
+
+  it('prefers the API title when the error is an Axios error with response data', () => {
+    const error = new AxiosError('Bad request')
+    error.response = {
+      status: 422,
+      data: { title: 'Validation failed' },
+    } as AxiosError['response']
+
+    handleServerError(error)
+
+    expect(toastError).toHaveBeenCalledWith('Validation failed')
+  })
+})

+ 4 - 2
src/lib/handle-server-error.ts

@@ -2,8 +2,10 @@ import { AxiosError } from 'axios'
 import { toast } from 'sonner'
 
 export function handleServerError(error: unknown) {
-  // eslint-disable-next-line no-console
-  console.log(error)
+  if (import.meta.env.DEV) {
+    // eslint-disable-next-line no-console
+    console.log(error)
+  }
 
   let errMsg = 'Something went wrong!'
 

+ 1 - 0
vite.config.ts

@@ -22,6 +22,7 @@ export default defineConfig({
     },
   },
   test: {
+    silent: 'passed-only',
     browser: {
       enabled: true,
       provider: playwright(),