Consider this Next.js component that fetches user data using a mocked fetch function. What will it render?
import React, { useEffect, useState } from 'react'; const mockFetch = () => Promise.resolve({ json: () => Promise.resolve({ name: 'Alice' }) }); export default function User() { const [user, setUser] = useState(null); useEffect(() => { mockFetch().then(res => res.json()).then(data => setUser(data)); }, []); if (!user) return <p>Loading...</p>; return <p>User: {user.name}</p>; }
Think about how useEffect and state updates work asynchronously.
The component starts with user as null, so it renders Loading.... After the mocked fetch resolves, user is set to the data, causing a re-render that shows User: Alice.
You want to mock the global fetch function in a Next.js test to return JSON data { message: 'Hello' }. Which option is correct?
Remember fetch returns a promise that resolves to a response object with a json() method that returns a promise.
Option D correctly mocks fetch as a jest function returning a promise resolving to an object with a json method that returns a promise resolving to the data.
Option D returns an object, not a promise, so it breaks the async pattern.
Option D returns a non-promise from fetch, causing errors.
Option D uses jest.mock incorrectly.
Given this mocked fetch in a Next.js component test, why does it cause a runtime error?
global.fetch = jest.fn(() => ({ json: () => ({ data: 'test' }) }));
Recall how the real fetch API behaves with promises.
The real fetch returns a promise resolving to a response object. The mock returns an object directly, so when the code calls fetch().then(...), it fails because the returned value is not a promise.
In this Next.js component, what will be the final value of data after the mocked fetch resolves?
import { useState, useEffect } from 'react'; const mockFetch = () => Promise.resolve({ json: () => Promise.resolve({ items: [1, 2, 3] }) }); export default function List() { const [data, setData] = useState([]); useEffect(() => { mockFetch() .then(res => res.json()) .then(json => setData(json.items)); }, []); return null; }
Look at what setData is called with after the fetch.
The mock fetch returns a response with a json method that resolves to an object with an items array. The component sets data to json.items, which is [1, 2, 3].
Why do developers mock the fetch API when testing Next.js components that fetch data?
Think about what can make tests flaky or slow when they depend on real network calls.
Mocking fetch isolates tests from real network calls, making them faster and more reliable by removing external dependencies and variability.
Option B is false; Next.js supports fetch but real calls are slow and flaky in tests.
Option B is false; mocking fetch still involves async code.
Option B is false; mocking fetch affects tests, not production performance.