Skip to content

Instantly share code, notes, and snippets.

@up1
Last active October 30, 2024 03:57
Show Gist options
  • Save up1/ddec44c64db6687912559b8db6e38558 to your computer and use it in GitHub Desktop.
Save up1/ddec44c64db6687912559b8db6e38558 to your computer and use it in GitHub Desktop.
Demo :: Fetch Mock
$node --test --experimental-test-coverage
▶ getUserById
✔ should fetch user data successfully (4.168291ms)
✔ getUserById (4.678666ms)
ℹ tests 1
ℹ suites 1
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 124.05
ℹ start of coverage report
ℹ ---------------------------------------------------------------
ℹ file | line % | branch % | funcs % | uncovered lines
ℹ ---------------------------------------------------------------
ℹ user.js | 66.67 | 50.00 | 100.00 | 6-7 12-14
ℹ user.test.js | 100.00 | 100.00 | 100.00 |
ℹ ---------------------------------------------------------------
ℹ all files | 91.94 | 71.43 | 100.00 |
ℹ ---------------------------------------------------------------
ℹ end of coverage report
export async function getUserById(userId) {
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) {
throw new Error(`Error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to fetch user:', error);
return null;
}
}
import fetchMock from "fetch-mock";
import { getUserById } from "./user.js";
import { test, describe } from "node:test";
import assert from "node:assert";
describe("getUserById", () => {
test("should fetch user data successfully", async () => {
// Arrange: Set up the mock response
const userId = 1;
const mockResponse = { id: 1, name: "Somkiat", email: "[email protected]" };
fetchMock
.mockGlobal()
.get(`https://api.example.com/users/${userId}`, mockResponse);
// Act: Call the function
const result = await getUserById(userId);
// Assert: Verify the response
assert.deepStrictEqual(result, mockResponse);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment