Skip to content

Stubbing docs dont run #2762

@ChaoticLeah

Description

@ChaoticLeah

The stubbing docs here dont work. There are multiple typescript errors but also ignoring that it does not assert equal

Example Code:

import { assertEquals } from "jsr:@std/assert";
import { stub } from "jsr:@std/testing/mock";

// Original function
function getUserName(id: number): string {
	// In a real app, this might call a database
	return "Original User";
}

// Function under test
function greetUser(id: number): string {
	const name = getUserName(id);
	return `Hello, ${name}!`;
}

Deno.test("greetUser with stubbed getUserName", () => {
	// Create a stub that returns a controlled value
	const getUserNameStub = stub(globalThis, "getUserName", () => "Test User");

	try {
		// Test with the stubbed function
		const greeting = greetUser(123);
		assertEquals(greeting, "Hello, Test User!");
	} finally {
		// Always restore the original function
		getUserNameStub.restore();
	}
});

Output:

-   Hello, Original User!
+   Hello, Test User!

It seems any use of globalThis doesnt actually work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions