Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(example): add new example for test stubs #1231

Merged
merged 3 commits into from
Dec 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions examples/stubs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* @title Stub functions
* @difficulty intermediate
* @tags cli, deploy
* @run <url>
* @resource {https://jsr.io/@std/testing/doc/mock#stubbing} Stub docs on JSR
* @resource {https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html} Typescript docs for `using` keyword
* @group Testing
*
* Test stubs are an extension of spys that also allows you to replace the method's internal behavior for testing purposes.
* In this example, we will demonstrate how we can use stubs to only test the desired behaviour.
*/

import { assertSpyCalls, returnsNext, stub } from "jsr:@std/testing/mock";
import { assertThrows } from "jsr:@std/assert";

type User = {
id: number;
name: string;
};

function getUserById(id: number): User | undefined {
// Actual database call would be here
return { id, name: "Ada Lovelace" };
}

const database = { getUserById };

class UserRepository {
static findOrThrow(id: number): User {
const user = database.getUserById(id);
if (!user) {
throw new Error("User not found");
}
return user;
}
}

// As we want to test the `findOrThrow` method, we don't actually need to access the database
Deno.test("findOrThrow method throws when the user was not found", () => {
// Stub the `getUserById` function to return `undefined` when called.
using dbStub = stub(database, "getUserById", returnsNext([undefined]));

// We expect this function call to throw an error
assertThrows(() => UserRepository.findOrThrow(1), Error, "User not found");
assertSpyCalls(dbStub, 1);
});
Loading