Bird
Raised Fist0
Denoframework~20 mins

Mocking and stubbing in Deno - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Mocking and Stubbing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this mocked function call?

Consider the following Deno test code using a stub to replace a function. What will be printed when the test runs?

Deno
import { stub } from "https://deno.land/std@0.203.0/testing/mock.ts";

function fetchData() {
  return "real data";
}

const fetchDataStub = stub(globalThis, "fetchData", () => "mocked data");

console.log(fetchData());

fetchDataStub.restore();
A"real data"
Bundefined
C"mocked data"
DThrows ReferenceError
Attempts:
2 left
💡 Hint

Think about where fetchData is defined and what window refers to in Deno.

❓ state_output
intermediate
2:00remaining
What is the value of call count after stubbing?

Given the following code using Deno's stub, what is the value of callCount after the calls?

Deno
import { stub } from "https://deno.land/std@0.203.0/testing/mock.ts";

const obj = {
  greet(name) {
    return `Hello, ${name}`;
  }
};

const greetStub = stub(obj, "greet", (name) => `Hi, ${name}`);

obj.greet("Alice");
obj.greet("Bob");

const callCount = greetStub.calls.length;

greetStub.restore();
AThrows TypeError
B1
C0
D2
Attempts:
2 left
💡 Hint

Count how many times the stubbed function is called.

📝 Syntax
advanced
2:00remaining
Which option correctly stubs a method with async behavior?

Which code snippet correctly stubs an async method fetchUser on api to return a resolved promise with {id: 1}?

Astub(api, "fetchUser", async () => { return {id: 1}; })
Bstub(api, "fetchUser", () => { return {id: 1}; })
Cstub(api, "fetchUser", () => Promise.resolve({id: 1}))
Dstub(api, "fetchUser", async () => Promise.resolve({id: 1}))
Attempts:
2 left
💡 Hint

Remember how async functions return promises automatically.

🔧 Debug
advanced
2:00remaining
Why does this stub not record calls?

Given this code, why does stub.calls.length remain 0 after calling obj.method()?

Deno
import { stub } from "https://deno.land/std@0.203.0/testing/mock.ts";

const obj = {
  method() {
    return "original";
  }
};

const callResult = obj.method.bind(obj)();

const stubMethod = stub(obj, "method", () => "stubbed");

const callCount = stubMethod.calls.length;

stubMethod.restore();
ABecause the stub function does not return a value
BBecause the stub was not called; binding creates a new function that bypasses the stub
CBecause the stub was restored before the call
DBecause the stub was created on the wrong object
Attempts:
2 left
💡 Hint

Think about what bind does to a function reference.

🧠 Conceptual
expert
2:00remaining
What is the main difference between mocking and stubbing in Deno tests?

Choose the best explanation of the difference between mocking and stubbing when testing with Deno's standard library.

AStubbing replaces a function's behavior with a fixed response; mocking also tracks calls and can verify call order and arguments
BStubbing is used only for async functions; mocking is for synchronous functions
CMocking replaces functions with empty implementations; stubbing records calls but does not change behavior
DMocking and stubbing are the same in Deno and can be used interchangeably
Attempts:
2 left
💡 Hint

Think about what extra features mocks provide beyond stubs.

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

  1. 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.
  2. Step 2: Identify the purpose in testing context

    They help test code without relying on real dependencies, making tests simpler and more reliable.
  3. Final Answer:

    To replace parts of code with fake versions for easier testing -> Option B
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    import { stub } from "https://deno.land/std/testing/mock.ts"; -> Option C
  4. 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?
import { stub } from "https://deno.land/std/testing/mock.ts";

const obj = {
  greet() {
    return "Hello";
  }
};

const stubGreet = stub(obj, "greet", () => "Hi there!");
console.log(obj.greet());
stubGreet.restore();
console.log(obj.greet());
medium
A. "Hello" then "Hello"
B. "Hi there!" then "Hi there!"
C. Runtime error due to incorrect stub usage
D. "Hi there!" then "Hello"

Solution

  1. Step 1: Understand stub behavior on method

    The stub replaces obj.greet with a new function returning "Hi there!" temporarily.
  2. Step 2: Analyze console outputs

    First console.log calls stubbed method, outputting "Hi there!". After restore(), original method returns "Hello" on second log.
  3. Final Answer:

    "Hi there!" then "Hello" -> Option D
  4. Quick Check:

    Stub replaces then restores method [OK]
Hint: Stub changes method until restore is called [OK]
Common Mistakes:
  • Expecting original method output before restore
  • Thinking stub permanently changes method
  • Confusing stub with spy that tracks calls
4. What is the error in the following Deno test code using stub?
import { stub } from "https://deno.land/std/testing/mock.ts";

const obj = {
  value() {
    return 42;
  }
};

const stubValue = stub(obj, "val", () => 100);
console.log(obj.value());
stubValue.restore();
medium
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

  1. Step 1: Check stub target method name

    The stub tries to replace method named "val" but obj only has "value" method.
  2. Step 2: Understand stub behavior on invalid method

    Stubbing a non-existent method causes an error or does not work as expected.
  3. Final Answer:

    Trying to stub a non-existent method 'val' on obj -> Option A
  4. 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

  1. 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 }.
  2. Step 2: Restore original method after test

    Store the stub in a variable and call restore() after the test to revert changes.
  3. Final Answer:

    Use const stubFetch = stub(obj, "fetchData", () => ({ success: true })); then call stubFetch.restore() after test -> Option A
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard