📖 Scenario: You are building a simple user service that fetches user data from an external API. To test your service without calling the real API, you will use mocking and stubbing techniques in Deno.
🎯 Goal: Create a test that mocks the external API call and stubs the response to verify your user service behaves correctly without making real network requests.
📋 What You'll Learn
Create a function fetchUser that calls an external API URL.
Create a variable mockResponse to hold the stubbed user data.
Write a test that mocks fetch to return mockResponse.
Complete the test by asserting the user service returns the stubbed data.
💡 Why This Matters
🌍 Real World
Mocking and stubbing are essential for testing code that depends on external services, allowing tests to run quickly and reliably without network access.
💼 Career
Understanding how to mock and stub in Deno is valuable for backend and full-stack developers writing automated tests to ensure code quality and prevent bugs.
Progress0 / 4 steps
1
Create the user fetching function
Write a function called fetchUser that takes a userId string and returns the result of calling fetch on the URL `https://api.example.com/users/${userId}`. Use await and response.json() to return the parsed JSON data.
Deno
Hint
Use template literals to build the URL and await to wait for the fetch and JSON parsing.
2
Create the mock response data
Create a constant variable called mockResponse that holds an object with id set to "123" and name set to "Alice".
Deno
Hint
Use an object literal with exact keys and values as shown.
3
Write a test that mocks fetch
Write a test named testFetchUser using Deno.test. Inside the test, mock the global fetch function to return a Promise resolving to an object with a json method that returns mockResponse. Then call fetchUser("123") and store the result in user.
Deno
Hint
Override globalThis.fetch with a function returning a resolved Promise with a json method returning mockResponse.
4
Assert the stubbed data is returned
Inside the testFetchUser test, add an assertion using Deno.assertEquals to check that user equals mockResponse.
Deno
Hint
Use assertEquals from Deno's standard asserts module to compare user and mockResponse.
Practice
(1/5)
1. What is the main purpose of mocking and stubbing in Deno testing?
easy
A. To speed up the execution of the entire program
B. To replace parts of code with fake versions for easier testing
C. To permanently change the behavior of functions in production
D. To automatically generate user interface components
Solution
Step 1: Understand mocking and stubbing
Mocking and stubbing are techniques used to replace parts of code with fake versions to isolate and test specific behaviors.
Step 2: Identify the purpose in testing context
They help test code without relying on real dependencies, making tests simpler and more reliable.
Final Answer:
To replace parts of code with fake versions for easier testing -> Option B
Quick Check:
Mocking purpose = Replace code parts [OK]
Hint: Mocking replaces code parts to isolate tests [OK]
Common Mistakes:
Thinking mocking speeds up the whole program
Believing mocks change production code permanently
Confusing mocking with UI generation
2. Which of the following is the correct way to import the stub function from Deno's standard testing library?
easy
A. import { stub } from "https://deno.land/std/testing/stub.ts";
B. import stub from "https://deno.land/std/testing/mock.ts";
C. import { stub } from "https://deno.land/std/testing/mock.ts";
D. import * as stub from "https://deno.land/std/testing/mock.ts";
Solution
Step 1: Recall the correct import path and syntax
The stub function is exported from "https://deno.land/std/testing/mock.ts" and must be imported using named import syntax.
Step 2: Check each option
import { stub } from "https://deno.land/std/testing/mock.ts"; uses named import from the correct path. import stub from "https://deno.land/std/testing/mock.ts"; uses default import which is incorrect. import { stub } from "https://deno.land/std/testing/stub.ts"; uses wrong file name. import * as stub from "https://deno.land/std/testing/mock.ts"; imports all as an object, not the function directly.
Final Answer:
import { stub } from "https://deno.land/std/testing/mock.ts"; -> Option C
Quick Check:
Correct import = named from mock.ts [OK]
Hint: Use named import from mock.ts for stub [OK]
Common Mistakes:
Using default import instead of named import
Wrong file path for stub
Importing everything instead of just stub
3. Given the following code snippet, what will be the output?
A. Trying to stub a non-existent method 'val' on obj
B. Missing import statement for stub
C. restore() called before stub is created
D. Incorrect arrow function syntax in stub
Solution
Step 1: Check stub target method name
The stub tries to replace method named "val" but obj only has "value" method.
Step 2: Understand stub behavior on invalid method
Stubbing a non-existent method causes an error or does not work as expected.
Final Answer:
Trying to stub a non-existent method 'val' on obj -> Option A
Quick Check:
Stub method must exist on object [OK]
Hint: Stub only existing methods on objects [OK]
Common Mistakes:
Using wrong method name in stub
Forgetting to import stub
Calling restore too early
5. You want to test a function that calls fetchData() which normally fetches data from the internet. Using Deno's stub, how can you replace fetchData to return a fixed value { success: true } only during the test, and ensure the original fetchData is restored after the test?
hard
A. Use const stubFetch = stub(obj, "fetchData", () => ({ success: true })); then call stubFetch.restore() after test
B. Replace fetchData globally without restore, returning fixed value
C. Use stub(obj, "fetchData", async () => Promise.resolve({ success: true })); but forget to restore
D. Call stub(obj, "fetchData", () => { return true; }); without storing stub
Solution
Step 1: Create a stub for fetchData returning fixed value
Use stub on the object containing fetchData, replacing it with a function returning { success: true }.
Step 2: Restore original method after test
Store the stub in a variable and call restore() after the test to revert changes.
Final Answer:
Use const stubFetch = stub(obj, "fetchData", () => ({ success: true })); then call stubFetch.restore() after test -> Option A
Quick Check:
Stub with restore keeps tests clean [OK]
Hint: Always restore stub after test to keep original code [OK]
Common Mistakes:
Not restoring stub after test
Replacing globally without control
Returning wrong stub value type
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.