import { assertEquals } from "jsr:@std/assert";
import { assertSpyCall, assertSpyCalls, stub } from "jsr:@std/testing/mock";
class UserService {
async getUser(id: string) {
// Complex database query
return { id, name: "Database User" };
}
async formatUser(user: { id: string; name: string }) {
return {
...user,
displayName: user.name.toUpperCase(),
};
}
async getUserFormatted(id: string) {
const user = await this.getUser(id);
return this.formatUser(user);
}
}
Deno.test("partial mocking with spies", async () => {
const service = new UserService();
// Only mock the getUser method
const getUserSpy = stub(
service,
"getUser",
() => Promise.resolve({ id: "test-id", name: "Mocked User" }),
);
try {
// The formatUser method will still use the real implementation
const result = await service.getUserFormatted("test-id");
assertEquals(result, {
id: "test-id",
name: "Mocked User",
displayName: "MOCKED USER",
});
// Verify getUser was called with the right arguments
assertSpyCalls(getUserSpy, 1);
assertSpyCall(getUserSpy, 0, {
args: ["test-id"],
});
} finally {
getUserSpy.restore();
}
});