Last active
October 30, 2024 03:57
-
-
Save up1/ddec44c64db6687912559b8db6e38558 to your computer and use it in GitHub Desktop.
Demo :: Fetch Mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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