Consider the following Deno test code using a stub to replace a function. What will be printed when the test runs?
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();
Think about where fetchData is defined and what window refers to in Deno.
In Deno, window is an alias for globalThis, so stubbing globalThis.fetchData works if fetchData is defined on globalThis. However, in this code, fetchData is a local function and not a property of globalThis, so stubbing globalThis.fetchData adds a new property. The call to fetchData() calls the local function, returning "real data". But since the stub is on globalThis.fetchData, it does not affect the local function. Therefore, the output is "real data".
Given the following code using Deno's stub, what is the value of callCount after the calls?
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();
Count how many times the stubbed function is called.
The stub replaces obj.greet. It is called twice, so greetStub.calls.length is 2.
Which code snippet correctly stubs an async method fetchUser on api to return a resolved promise with {id: 1}?
Remember how async functions return promises automatically.
Option A defines an async function that returns the object, automatically wrapping it in a resolved promise. Option A returns a promise from within an async function, resulting in Promise<Promise<{id: 1}>> (incorrect). Option A returns a promise but lacks the async keyword. Option A returns a plain object (not a promise). Deno stubs work with either async functions or functions returning promises, but D best matches an async original method.
Given this code, why does stub.calls.length remain 0 after calling obj.method()?
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();
Think about what bind does to a function reference.
Using obj.method.bind(obj)() *before* stubbing captures and calls the original method via the bound function. The stub replacement happens afterward, so the stub is never called, and calls.length stays 0.
Choose the best explanation of the difference between mocking and stubbing when testing with Deno's standard library.
Think about what extra features mocks provide beyond stubs.
Stubs replace function behavior with fixed responses. Mocks do that too but also track how functions are called, allowing verification of call counts, arguments, and order.
