|
| 1 | +// @ts-nocheck |
| 2 | +import { test, describe, before, after } from "node:test"; |
| 3 | +import assert from "node:assert/strict"; |
| 4 | +import request from "supertest"; |
| 5 | + |
| 6 | +import { MockAgent, setGlobalDispatcher } from "undici"; |
| 7 | + |
| 8 | +import express, { Router } from "express"; |
| 9 | + |
| 10 | +const hugo = (router = new Router()) => { |
| 11 | + router.get("/hugo", async (_request, res) => { |
| 12 | + const userData = await fetch("https://api.github.com/users/HugoDF").then( |
| 13 | + (res) => res.json(), |
| 14 | + ); |
| 15 | + |
| 16 | + const { blog, location, bio, public_repos } = userData; |
| 17 | + return res.json({ |
| 18 | + blog, |
| 19 | + location, |
| 20 | + bio, |
| 21 | + publicRepos: public_repos, |
| 22 | + }); |
| 23 | + }); |
| 24 | + return router; |
| 25 | +}; |
| 26 | + |
| 27 | +const initHugo = () => { |
| 28 | + const app = express(); |
| 29 | + app.use(hugo()); |
| 30 | + return app; |
| 31 | +}; |
| 32 | + |
| 33 | +const mockAgent = new MockAgent(); |
| 34 | + |
| 35 | +describe("GET /hugo", () => { |
| 36 | + before(() => { |
| 37 | + mockAgent.disableNetConnect(); |
| 38 | + mockAgent.enableNetConnect("127.0.0.1"); |
| 39 | + setGlobalDispatcher(mockAgent); |
| 40 | + }); |
| 41 | + |
| 42 | + after(async () => { |
| 43 | + await mockAgent.close(); |
| 44 | + }); |
| 45 | + |
| 46 | + test("It should fetch HugoDF from GitHub", async () => { |
| 47 | + const ghMocks = mockAgent.get("https://api.github.com"); |
| 48 | + ghMocks.intercept({ path: "/users/HugoDF" }).reply(200, { |
| 49 | + blog: "https://codewithhugo.com", |
| 50 | + location: "London", |
| 51 | + bio: "Developer, JavaScript", |
| 52 | + public_repos: 39, |
| 53 | + }); |
| 54 | + |
| 55 | + const app = initHugo(); |
| 56 | + await request(app).get("/hugo"); |
| 57 | + |
| 58 | + mockAgent.assertNoPendingInterceptors(); |
| 59 | + assert.deepEqual(mockAgent.pendingInterceptors(), []); |
| 60 | + }); |
| 61 | + test("It should 200 and return a transformed version of GitHub response", async () => { |
| 62 | + const ghMocks = mockAgent.get("https://api.github.com"); |
| 63 | + ghMocks.intercept({ path: "/users/HugoDF" }).reply(200, { |
| 64 | + blog: "https://codewithhugo.com", |
| 65 | + location: "London", |
| 66 | + bio: "Developer, JavaScript", |
| 67 | + public_repos: 39, |
| 68 | + }); |
| 69 | + |
| 70 | + const app = initHugo(); |
| 71 | + const res = await request(app).get("/hugo"); |
| 72 | + |
| 73 | + assert.deepEqual(res.body, { |
| 74 | + blog: "https://codewithhugo.com", |
| 75 | + location: "London", |
| 76 | + bio: "Developer, JavaScript", |
| 77 | + publicRepos: 39, |
| 78 | + }); |
| 79 | + }); |
| 80 | +}); |
0 commit comments