Performance: Mocking and stubbing
Mocking and stubbing affect test execution speed and resource usage during development but do not impact production page load or rendering.
import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; Deno.test("mock fetch API", async () => { globalThis.fetch = async () => ({ json: async () => ({ success: true }), }); const response = await fetch("https://api.example.com/data"); const data = await response.json(); assertEquals(data.success, true); });
import { assertEquals } from "https://deno.land/std/testing/asserts.ts"; Deno.test("fetch real API", async () => { const response = await fetch("https://api.example.com/data"); const data = await response.json(); assertEquals(data.success, true); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Real network calls in tests | 0 | 0 | 0 | [✗] Bad |
| Mocked network calls in tests | 0 | 0 | 0 | [✓] Good |
stub function from Deno's standard testing library?stub function is exported from "https://deno.land/std/testing/mock.ts" and must be imported using named import syntax.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());obj.greet with a new function returning "Hi there!" temporarily.console.log calls stubbed method, outputting "Hi there!". After restore(), original method returns "Hello" on second log.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();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?stub on the object containing fetchData, replacing it with a function returning { success: true }.restore() after the test to revert changes.const stubFetch = stub(obj, "fetchData", () => ({ success: true })); then call stubFetch.restore() after test -> Option APass the test and this pattern moves unknown