Next.js 14 is the latest version of the popular React-based framework. With this version, many developers have started to use Vitest as their testing framework of choice. Vitest is a lightweight, fast, and extensible testing framework that can be used for both unit and integration testing.
In this article, we will be focusing on the issue of mocking fetch requests in Next.js 14 using Vitest. Specifically, we will be looking at the issue of Vitest not recognizing the use of the .formData() method to create a new FormData object. This issue can cause tests to fail, and we will be providing a solution to this problem.
The Issue
When testing a Next.js 14 application using Vitest, you may encounter an issue where the fetch API is not properly mocked. This can be especially problematic if you are using the .formData() method to create a new FormData object.
For example, if you have a test that uses the following code:
const response = await fetch('/api/submit-form', {
method: 'POST',
body: new FormData(),
headers: {
'Content-Type': 'multipart/form-data'
}
});
const data = await response.json();
expect(data).toEqual({ success: true });
You may encounter an error where Vitest does not recognize the use of new FormData() and the test fails.
The Solution
To solve this issue, you can use the msw library to create a mock service worker. This will allow you to mock the fetch API and create a mock response for your test.
First, you will need to install the msw library:
npm install msw
Next, you will need to create a mock service worker file. This file will define the mock handlers for the fetch API:
import { setupWorker, rest } from 'msw'
const worker = setupWorker(
rest.post('/api/submit-form', (req, res, ctx) => {
return res(
ctx.json({
success: true
})
)
})
)
export default worker
You can then use this mock service worker in your test:
import { setupWorker, rest } from 'msw'
import worker from './mocks/mockServiceWorker'
beforeAll(() => worker.start())
afterAll(() => worker.stop())
test('submits form', async () => {
const response = await fetch('/api/submit-form', {
method: 'POST',
body: new FormData(),
headers: {
'Content-Type': 'multipart/form-data'
}
})
const data = await response.json()
expect(data).toEqual({ success: true })
})
This will allow you to properly mock the fetch API and use the .formData() method to create a new FormData object in your test.
Mocking the fetch API in Next.js 14 using Vitest can be a challenge, especially when using the .formData() method to create a new FormData object. However, by using the msw library to create a mock service worker, you can properly mock the fetch API and ensure that your tests are running correctly.
References
| Title | Link |
|---|---|
| Next.js 14 | https://nextjs.org/ |
| Vitest | https://vitest.dev/ |
| msw | https://mswjs.io/ |