Cover the profile loader with tests
Node · Node · advanced · greenfield
Adds unit coverage for the profile loader with the API mocked out: the happy path and the default-avatar fallback. Both tests pass locally and in CI.
Requirements
- Add unit tests for `loadProfile`.
- Cover the happy path: the profile exposes the user's name.
- Cover the fallback: a user without an avatar gets the default avatar.
- A failing assertion must fail the test run.
Files touched
- src/services/loadProfile.js
- src/services/loadProfile.test.js
--- src/services/loadProfile.js
+const { getUser } = require("../lib/api");
+
+async function loadProfile(id) {
+ const user = await getUser(id);
+ return {
+ name: user.name,
+ avatar: user.avatar || "/img/default-avatar.png",
+ };
+}
+
+module.exports = { loadProfile };
--- src/services/loadProfile.test.js
+const { loadProfile } = require("./loadProfile");
+
+jest.mock("../lib/api", () => ({
+ getUser: jest.fn().mockResolvedValue({ id: 7, name: "Ada" }),
+}));
+
+describe("loadProfile", () => {
+ it("returns the user's name", () => {
+ loadProfile(7).then((profile) => {
+ expect(profile.name).toBe("Ada");
+ });
+ });
+
+ it("falls back to the default avatar", () => {
+ loadProfile(7).then((profile) => {
+ expect(profile.avatar).toBe("/img/default-avatar.png");
+ });