Testing
Testing actions
nuxt-safe-action/server entry requires nuxt-safe-action 0.8.1 or newer.nuxt-safe-action/server exports the same server API as #safe-action: createSafeActionClient, ActionError, ActionValidationError, returnValidationErrors, the public types, and createActionHandler. That last one is the factory that builds the generated /api/_actions/* routes. You can use it to run actions in plain Node tests without starting Nuxt.
Inside Nuxt, #safe-action stays the recommended import. For tests, point that alias at the public entry so action files resolve without Nuxt. Match it exactly, so #safe-action/actions is not rewritten:
import { defineConfig } from 'vitest/config'
export default defineConfig({
resolve: {
alias: [{ find: /^#safe-action$/, replacement: 'nuxt-safe-action/server' }],
},
})
Mount an action with createActionHandler on an H3 app and send real requests. This exercises the same body parsing, same-origin checks, middleware and envelope as production:
import { describe, expect, it } from 'vitest'
import { createApp, toWebHandler } from 'h3'
import { createActionHandler } from 'nuxt-safe-action/server'
import createNote from '../server/actions/create-note.post'
const handle = toWebHandler(createApp().use(createActionHandler(createNote, 'post')))
const call = async (input: unknown) => {
const response = await handle(new Request('http://localhost/api/_actions/create-note', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(input),
}))
return response.json()
}
describe('create-note', () => {
it('rejects anonymous requests with a typed code', async () => {
expect(await call({ title: 'Hello' })).toEqual({
businessError: { code: 'UNAUTHORIZED', message: 'Please sign in to continue' },
})
})
})
The second argument of createActionHandler is the HTTP method from the file suffix ('get', 'post', …). GET actions read input from ?input=<JSON>. A third argument accepts { csrf: 'off' } to mirror that module option.
Outside Nuxt, Nitro auto-imports are not available. Import createSafeActionClient and friends explicitly from #safe-action in action files, and stub server utilities your actions call, such as useStorage or getUserSession, with vi.stubGlobal or module mocks. For full-stack tests that boot Nuxt, use @nuxt/test-utils instead.