|
| 1 | +import * as z from 'zod' |
| 2 | +import { Hono } from 'hono' |
| 3 | +import { hc } from 'hono/client' |
| 4 | +import { parseWithZod } from '@conform-to/zod' |
| 5 | +import { conformValidator } from '../src' |
| 6 | +import { vi } from 'vitest' |
| 7 | + |
| 8 | +describe('Validate the hook option processing', () => { |
| 9 | + const app = new Hono() |
| 10 | + const schema = z.object({ name: z.string() }) |
| 11 | + const hookMockFn = vi.fn((submission, c) => { |
| 12 | + if (submission.status !== 'success') { |
| 13 | + return c.json({ success: false, message: 'Bad Request' }, 400) |
| 14 | + } |
| 15 | + }) |
| 16 | + const handlerMockFn = vi.fn((c) => { |
| 17 | + const submission = c.req.valid('form') |
| 18 | + const value = submission.value |
| 19 | + return c.json({ success: true, message: `name is ${value.name}` }) |
| 20 | + }) |
| 21 | + const route = app.post( |
| 22 | + '/author', |
| 23 | + conformValidator((formData) => parseWithZod(formData, { schema }), hookMockFn), |
| 24 | + handlerMockFn |
| 25 | + ) |
| 26 | + const client = hc<typeof route>('http://localhost', { |
| 27 | + fetch: (req, init) => { |
| 28 | + return app.request(req, init) |
| 29 | + }, |
| 30 | + }) |
| 31 | + |
| 32 | + afterEach(() => { |
| 33 | + hookMockFn.mockClear() |
| 34 | + handlerMockFn.mockClear() |
| 35 | + }) |
| 36 | + |
| 37 | + it('Should called hook function', async () => { |
| 38 | + await client.author.$post({ form: { name: 'Space Cat' } }) |
| 39 | + expect(hookMockFn).toHaveBeenCalledTimes(1) |
| 40 | + }) |
| 41 | + |
| 42 | + describe('When the hook return Response', () => { |
| 43 | + it('Should return response that the hook returned', async () => { |
| 44 | + const req = new Request('http://localhost/author', { body: new FormData(), method: 'POST' }) |
| 45 | + const res = (await app.request(req)).clone() |
| 46 | + const hookRes = hookMockFn.mock.results[0].value.clone() |
| 47 | + expect(hookMockFn).toHaveReturnedWith(expect.any(Response)) |
| 48 | + expect(res.status).toBe(hookRes.status) |
| 49 | + expect(await res.json()).toStrictEqual(await hookRes.json()) |
| 50 | + }) |
| 51 | + }) |
| 52 | + |
| 53 | + describe('When the hook not return Response', () => { |
| 54 | + it('Should return response that the handler function returned', async () => { |
| 55 | + const res = (await client.author.$post({ form: { name: 'Space Cat' } })).clone() |
| 56 | + const handlerRes = handlerMockFn.mock.results[0].value.clone() |
| 57 | + expect(hookMockFn).not.toHaveReturnedWith(expect.any(Response)) |
| 58 | + expect(res.status).toBe(handlerRes.status) |
| 59 | + expect(await res.json()).toStrictEqual(await handlerRes.json()) |
| 60 | + }) |
| 61 | + }) |
| 62 | +}) |
0 commit comments