Bird
Raised Fist0
NextJSframework~20 mins

Mocking data fetching in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mocking Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What will this Next.js component render when data fetching is mocked?

Consider this Next.js component that fetches user data using a mocked fetch function. What will it render?

NextJS
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>;
}
A<p>Loading...</p> initially, then <p>User: Alice</p>
B<p>User: Alice</p> immediately without loading state
CComponent throws an error because mockFetch is not defined
D<p>Loading...</p> forever, never showing user name
Attempts:
2 left
💡 Hint

Think about how useEffect and state updates work asynchronously.

📝 Syntax
intermediate
2:00remaining
Which option correctly mocks fetch in a Next.js test?

You want to mock the global fetch function in a Next.js test to return JSON data { message: 'Hello' }. Which option is correct?

Aglobal.fetch = () => ({ json: () => ({ message: 'Hello' }) });
Bglobal.fetch = jest.fn(() => ({ json: () => Promise.resolve({ message: 'Hello' }) }));
Cglobal.fetch = jest.mock(() => Promise.resolve({ message: 'Hello' }));
Dglobal.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve({ message: 'Hello' }) }));
Attempts:
2 left
💡 Hint

Remember fetch returns a promise that resolves to a response object with a json() method that returns a promise.

🔧 Debug
advanced
2:00remaining
Why does this mocked fetch cause a runtime error in Next.js?

Given this mocked fetch in a Next.js component test, why does it cause a runtime error?

NextJS
global.fetch = jest.fn(() => ({ json: () => ({ data: 'test' }) }));
Afetch must return a promise, but this returns an object, causing a runtime error
Bjson method must return an object, but this returns a promise, causing a runtime error
Cjest.fn cannot be used to mock fetch globally
DThe fetch mock is missing a call to next() causing infinite loop
Attempts:
2 left
💡 Hint

Recall how the real fetch API behaves with promises.

❓ state_output
advanced
2:00remaining
What is the final state of data after this mocked fetch in Next.js?

In this Next.js component, what will be the final value of data after the mocked fetch resolves?

NextJS
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;
}
A[{ items: [1, 2, 3] }]
B[] (empty array)
C[1, 2, 3]
Dundefined
Attempts:
2 left
💡 Hint

Look at what setData is called with after the fetch.

🧠 Conceptual
expert
2:00remaining
Which statement best explains why mocking fetch is important in Next.js testing?

Why do developers mock the fetch API when testing Next.js components that fetch data?

ABecause Next.js does not support real fetch calls during tests
BTo isolate component logic from network variability and ensure tests run fast and reliably
CTo avoid writing asynchronous code in tests
DBecause mocking fetch automatically improves component performance in production
Attempts:
2 left
💡 Hint

Think about what can make tests flaky or slow when they depend on real network calls.

Practice

(1/5)
1. What is the main purpose of mocking data fetching in a Next.js app?
easy
A. To encrypt data before sending it
B. To speed up the production server
C. To permanently store data on the client
D. To simulate data retrieval without needing a real server

Solution

  1. Step 1: Understand mocking concept

    Mocking means pretending to get data, so you don't rely on a real server.
  2. Step 2: Identify purpose in Next.js

    This helps build and test UI without waiting for real backend responses.
  3. Final Answer:

    To simulate data retrieval without needing a real server -> Option D
  4. Quick Check:

    Mocking = Simulate data fetching [OK]
Hint: Mocking means faking data to test without a real server [OK]
Common Mistakes:
  • Thinking mocking speeds up production
  • Confusing mocking with data storage
  • Assuming mocking encrypts data
2. Which of the following is the correct way to create a mock async data fetch function in Next.js?
easy
A. async function fetchData() { return new Promise(resolve => setTimeout(() => resolve({ data: [] }), 1000)); }
B. const fetchData = () => { return { data: [] }; }
C. function fetchData() { setTimeout(() => { return { data: [] }; }, 1000); }
D. const fetchData = async () => { return setTimeout(() => ({ data: [] }), 1000); }

Solution

  1. Step 1: Check async function syntax

    async function fetchData() { return new Promise(resolve => setTimeout(() => resolve({ data: [] }), 1000)); } correctly returns a Promise that resolves after 1 second with data.
  2. Step 2: Identify incorrect patterns

    const fetchData = () => { return { data: [] }; } is synchronous, C does not return a Promise, D returns timeout ID, not data.
  3. Final Answer:

    async function fetchData() { return new Promise(resolve => setTimeout(() => resolve({ data: [] }), 1000)); } -> Option A
  4. Quick Check:

    Async + Promise + delay = async function fetchData() { return new Promise(resolve => setTimeout(() => resolve({ data: [] }), 1000)); } [OK]
Hint: Async functions must return a Promise to mock delays [OK]
Common Mistakes:
  • Returning data synchronously without Promise
  • Using setTimeout without Promise
  • Returning timeout ID instead of data
3. Given this mock fetch function in Next.js:
async function fetchData() {
  return new Promise(resolve => setTimeout(() => resolve({ users: ["Alice", "Bob"] }), 500));
}

fetchData().then(data => console.log(data.users));

What will be logged to the console?
medium
A. Promise { <pending> }
B. undefined
C. ["Alice", "Bob"]
D. Error: fetchData is not a function

Solution

  1. Step 1: Understand the Promise resolution

    The function returns a Promise that resolves after 500ms with an object containing users array.
  2. Step 2: Check the then callback

    The then callback logs data.users, which is ["Alice", "Bob"].
  3. Final Answer:

    ["Alice", "Bob"] -> Option C
  4. Quick Check:

    Promise resolves to users array logged [OK]
Hint: Promise.then logs resolved data, not the Promise itself [OK]
Common Mistakes:
  • Expecting immediate data without waiting
  • Logging the Promise object instead of resolved value
  • Confusing function call with undefined
4. Identify the error in this mock data fetch function:
async function fetchData() {
  setTimeout(() => {
    return { data: [1, 2, 3] };
  }, 1000);
}
medium
A. setTimeout cannot be used inside async functions
B. The function does not return a Promise, so data is undefined
C. The return statement inside setTimeout is invalid syntax
D. The function should not be async if using setTimeout

Solution

  1. Step 1: Analyze return behavior

    The function does not return anything; setTimeout callback's return is ignored.
  2. Step 2: Understand async function expectations

    Async functions should return a Promise; here, no Promise is returned, so caller gets undefined.
  3. Final Answer:

    The function does not return a Promise, so data is undefined -> Option B
  4. Quick Check:

    Async function must return Promise, not just use setTimeout [OK]
Hint: Return a Promise to deliver data after delay [OK]
Common Mistakes:
  • Assuming setTimeout return affects function return
  • Thinking async forbids setTimeout
  • Ignoring that async functions return Promises
5. You want to mock fetching user profiles with a delay and filter out users with empty names. Which code correctly mocks this in Next.js?
hard
A. async function fetchUsers() { const users = [{ name: "", id: 1 }, { name: "Eve", id: 2 }]; return new Promise(resolve => setTimeout(() => resolve(users.filter(u => u.name)), 1000)); }
B. function fetchUsers() { return [{ name: "", id: 1 }, { name: "Eve", id: 2 }].filter(u => u.name); }
C. async function fetchUsers() { const users = [{ name: "", id: 1 }, { name: "Eve", id: 2 }]; return users.filter(u => u.name); }
D. async function fetchUsers() { return new Promise(resolve => setTimeout(() => resolve([{ name: "", id: 1 }, { name: "Eve", id: 2 }]), 1000)); }

Solution

  1. Step 1: Identify filtering and delay

    async function fetchUsers() { const users = [{ name: "", id: 1 }, { name: "Eve", id: 2 }]; return new Promise(resolve => setTimeout(() => resolve(users.filter(u => u.name)), 1000)); } filters out users with empty names and returns a Promise resolving after 1 second.
  2. Step 2: Check other options

    A returns unfiltered data with delay, B performs filtering but is synchronous and non-async without delay, C returns filtered data synchronously without delay.
  3. Final Answer:

    async function fetchUsers() { const users = [{ name: "", id: 1 }, { name: "Eve", id: 2 }]; return new Promise(resolve => setTimeout(() => resolve(users.filter(u => u.name)), 1000)); } -> Option A
  4. Quick Check:

    Filter then delay with Promise = async function fetchUsers() { const users = [{ name: "", id: 1 }, { name: "Eve", id: 2 }]; return new Promise(resolve => setTimeout(() => resolve(users.filter(u => u.name)), 1000)); } [OK]
Hint: Filter data before resolving Promise with delay [OK]
Common Mistakes:
  • Not filtering data before resolving
  • Returning data synchronously without delay
  • Using non-async functions for async behavior
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard