0
0
NextJSframework~30 mins

Testing server actions in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing Server Actions in Next.js 14
📖 Scenario: You are building a simple Next.js 14 app that lets users submit feedback. You want to test the server action that saves the feedback to ensure it works correctly.
🎯 Goal: Create a server action function to save feedback, then write a test to verify it saves the data as expected.
📋 What You'll Learn
Create a server action function called saveFeedback that accepts a feedback string parameter
Create a test file that imports saveFeedback
Write a test case that calls saveFeedback with a sample string and checks the result
Use Next.js 14 server action patterns and modern testing syntax
💡 Why This Matters
🌍 Real World
Server actions in Next.js 14 let you write backend logic that can be tested independently, improving app reliability.
💼 Career
Testing server actions is a key skill for Next.js developers to ensure backend code works correctly and prevents bugs in production.
Progress0 / 4 steps
1
Create the server action function
Create a server action function called saveFeedback in a file named actions.ts. It should accept a single parameter feedback of type string and return an object with a message property set to `Feedback received: ${feedback}`.
NextJS
Need a hint?

Use an async function that returns an object with a message string using a template literal.

2
Set up the test file
Create a test file named actions.test.ts. Import the saveFeedback function from ./actions. Also, import describe, it, and expect from vitest.
NextJS
Need a hint?

Use import statements to bring in saveFeedback and testing functions from vitest.

3
Write a test case for the server action
Inside the test file, write a test case using describe and it. The test should call saveFeedback with the string 'Great app!' and use expect to check that the returned object's message property equals 'Feedback received: Great app!'.
NextJS
Need a hint?

Use await to call saveFeedback and expect(...).toBe(...) to check the message.

4
Complete the test setup with export
Ensure the test file exports nothing extra and the server action remains exported. Confirm the test file ends with the test suite code and the saveFeedback function is exported from actions.ts.
NextJS
Need a hint?

No extra exports needed. Just confirm the function and tests are present as before.