Testing server actions helps make sure your backend code works correctly before users see it. It catches mistakes early and keeps your app reliable.
0
0
Testing server actions in NextJS
Introduction
When you want to check if a server action correctly saves data to a database.
When you need to verify that a server action returns the right response for different inputs.
When you want to prevent bugs by testing server logic before deploying.
When you want to automate tests to run every time you update your code.
When you want to simulate user interactions that trigger server actions.
Syntax
NextJS
import { describe, it, expect } from 'vitest'; import { myServerAction } from './actions'; describe('myServerAction', () => { it('should return expected result', async () => { const inputData = {}; // define inputData appropriately const expectedOutput = {}; // define expectedOutput appropriately const result = await myServerAction(inputData); expect(result).toEqual(expectedOutput); }); });
Use describe to group related tests.
Use it to define a single test case.
Examples
This tests if the
addUser server action adds a user and returns success.NextJS
import { it, expect } from 'vitest'; import { addUser } from './actions'; it('adds a user successfully', async () => { const user = { name: 'Alice' }; const response = await addUser(user); expect(response.success).toBe(true); });
This checks that deleting a post with a wrong ID returns an error.
NextJS
import { it, expect } from 'vitest'; import { deletePost } from './actions'; it('fails to delete non-existing post', async () => { const response = await deletePost('invalid-id'); expect(response.error).toBeDefined(); });
Sample Program
This example shows a simple server action greet that returns a greeting message or an error. The tests check both cases.
NextJS
import { it, expect } from 'vitest'; // Example server action export async function greet(name) { if (!name) return { error: 'Name is required' }; return { message: `Hello, ${name}!` }; } // Test for the greet server action it('returns greeting message when name is provided', async () => { const result = await greet('Bob'); expect(result).toEqual({ message: 'Hello, Bob!' }); }); it('returns error when name is missing', async () => { const result = await greet(''); expect(result).toEqual({ error: 'Name is required' }); });
OutputSuccess
Important Notes
Server actions run on the server, so tests should run in a Node.js environment.
Use async/await to handle server actions that return promises.
Keep tests small and focused on one behavior at a time.
Summary
Testing server actions helps catch bugs early and keeps your backend reliable.
Use testing tools like Vitest to write simple tests for your server actions.
Write tests for both success and error cases to cover all possibilities.