Skip to content

Commit 03eb65d

Browse files
committed
test: use Node.js mock instead of esmock package
1 parent 90d5b66 commit 03eb65d

5 files changed

Lines changed: 62 additions & 59 deletions

File tree

package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
"prepublishOnly": "rimraf ./dist && npm run build && pkg-ok",
1818
"build": "node ./esbuild.config.js",
1919
"test": "npm run test-only && npm run lint",
20-
"test-only": "glob -c \"node --loader=esmock --no-warnings --test-concurrency 1 --test\" \"test/**/*.test.js\"",
20+
"test-only": "glob -c \"node --no-warnings --test-concurrency 1 --test\" \"test/**/*.test.js\"",
2121
"coverage": "c8 --reporter=lcov npm run test",
2222
"clear:cache": "node ./scripts/clear-cache.js"
2323
},
@@ -72,7 +72,6 @@
7272
"cross-env": "^7.0.3",
7373
"esbuild": "^0.25.0",
7474
"eslint-plugin-jsdoc": "^50.6.2",
75-
"esmock": "^2.6.7",
7675
"http-server": "^14.1.1",
7776
"pkg-ok": "^3.0.0",
7877
"pretty-bytes": "^7.0.0",

src/http-server/endpoints/flags.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Import Node.js Dependencies
2-
import { pipeline } from "node:stream";
2+
import stream from "node:stream";
33

44
// Import Third-party Dependencies
55
import send from "@polka/send-type";
@@ -19,7 +19,7 @@ export function get(req, res) {
1919

2020
res.writeHead(200, { "Content-Type": "text/html" });
2121

22-
return pipeline(lazyFetchFlagFile(req.params.title), res, (err) => {
22+
return stream.pipeline(lazyFetchFlagFile(req.params.title), res, (err) => {
2323
if (err) {
2424
console.error(err);
2525
}

src/http-server/index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ import * as middlewares from "./middlewares/index.js";
2222
import { appCache } from "../cache.js";
2323
import { WebSocketServerInstanciator } from "./websocket/index.js";
2424

25+
// CONSTANTS
26+
export const BROWSER = {
27+
open
28+
};
29+
2530
export function buildServer(dataFilePath, options = {}) {
2631
const httpConfigPort = typeof options.port === "number" ? options.port : 0;
2732
const openLink = typeof options.openLink === "boolean" ? options.openLink : true;
@@ -68,7 +73,7 @@ export function buildServer(dataFilePath, options = {}) {
6873
console.log(kleur.magenta().bold(await i18n.getToken("cli.http_server_started")), kleur.cyan().bold(link));
6974

7075
if (openLink) {
71-
open(link);
76+
BROWSER.open(link);
7277
}
7378
});
7479

test/commands/scorecard.test.js

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,16 @@ import { fileURLToPath } from "node:url";
33
import path from "node:path";
44
import { test } from "node:test";
55
import assert from "node:assert";
6+
import fs from "node:fs";
67

78
// Import Third-party Dependencies
8-
import esmock from "esmock";
99
import { API_URL } from "@nodesecure/ossf-scorecard-sdk";
1010
import { Ok } from "@openally/result";
1111

1212
// Import Internal Dependencies
1313
import { runProcess } from "../helpers/cliCommandRunner.js";
1414
import { arrayFromAsync, getExpectedScorecardLines } from "../helpers/utils.js";
15+
import { getCurrentRepository } from "../../src/commands/scorecard.js";
1516

1617
// CONSTANTS
1718
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -97,26 +98,19 @@ test("should not display scorecard for unknown repository", async() => {
9798
assert.deepEqual(givenLines, expectedLines, `lines should be ${expectedLines}`);
9899
});
99100

100-
test("should retrieve repository whithin git config", async() => {
101-
const testingModule = await esmock("../../src/commands/scorecard.js", {
102-
fs: {
103-
readFileSync: () => [
104-
"[remote \"origin\"]",
105-
"\turl = git@github.com:myawesome/repository.git"
106-
].join("\n")
107-
}
108-
});
101+
test("should retrieve repository within git config", async(ctx) => {
102+
const readFileResult = [
103+
"[remote \"origin\"]",
104+
"\turl = git@github.com:myawesome/repository.git"
105+
].join("\n");
106+
ctx.mock.method(fs, "readFileSync", () => readFileResult);
109107

110-
assert.deepEqual(testingModule.getCurrentRepository(), Ok(["myawesome/repository", "github"]));
108+
assert.deepEqual(getCurrentRepository(), Ok(["myawesome/repository", "github"]));
111109
});
112110

113-
test("should not find origin remote", async() => {
114-
const testingModule = await esmock("../../src/commands/scorecard.js", {
115-
fs: {
116-
readFileSync: () => "just one line"
117-
}
118-
});
119-
const result = testingModule.getCurrentRepository();
111+
test("should not find origin remote", async(ctx) => {
112+
ctx.mock.method(fs, "readFileSync", () => "just one line");
113+
const result = getCurrentRepository();
120114

121115
assert.equal(result.err, true);
122116
assert.equal(result.val, "Cannot find origin remote.");

test/httpServer.test.js

Lines changed: 41 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
11
// Import Node.js Dependencies
22
import fs from "node:fs";
33
import { fileURLToPath } from "node:url";
4-
import { after, before, describe, test } from "node:test";
4+
import { after, before, describe, test, mock } from "node:test";
55
import { once } from "node:events";
66
import path from "node:path";
77
import assert from "node:assert";
8+
import stream from "node:stream";
89

910
// Import Third-party Dependencies
1011
import { get, post, MockAgent, getGlobalDispatcher, setGlobalDispatcher } from "@myunisoft/httpie";
1112
import * as i18n from "@nodesecure/i18n";
1213
import * as flags from "@nodesecure/flags";
1314
import enableDestroy from "server-destroy";
14-
import esmock from "esmock";
1515
import cacache from "cacache";
1616

1717
// Import Internal Dependencies
18-
import { buildServer } from "../src/http-server/index.js";
18+
import { buildServer, BROWSER } from "../src/http-server/index.js";
1919
import { CACHE_PATH } from "../src/cache.js";
20+
import * as rootEndpoint from "../src/http-server/endpoints/root.js";
21+
import * as flagsEndpoint from "../src/http-server/endpoints/flags.js";
2022

2123
// CONSTANTS
2224
const kHttpPort = 17049;
@@ -69,20 +71,35 @@ describe("httpServer", { concurrency: 1 }, () => {
6971
assert.equal(result.headers["content-type"], "text/html");
7072
});
7173

72-
test("'/' should fail", async() => {
73-
const errors = [];
74-
const module = await esmock("../src/http-server/endpoints/root.js", {
75-
"@polka/send-type": {
76-
default: (_res, _status, { error }) => errors.push(error)
74+
test("'/' should fail", async(ctx) => {
75+
class Response {
76+
constructor() {
77+
this.body = "";
78+
this.headers = {};
79+
this.statusCode = 200;
7780
}
78-
});
79-
80-
await module.get({}, ({
81-
writeHead: () => {
82-
throw new Error("fake error");
81+
end(str) {
82+
this.body = str;
83+
}
84+
writeHead(int) {
85+
this.statusCode = int;
86+
}
87+
getHeader(key) {
88+
return this.headers[key];
8389
}
84-
}));
85-
assert.deepEqual(errors, ["fake error"]);
90+
}
91+
92+
const fakeError = "fake error";
93+
function toThrow() {
94+
throw new Error(fakeError);
95+
}
96+
ctx.mock.method(Response.prototype, "writeHead", toThrow, { times: 1 });
97+
98+
const response = new Response();
99+
await rootEndpoint.get({}, response);
100+
101+
assert.strictEqual(response.body, JSON.stringify({ error: fakeError }));
102+
assert.strictEqual(response.statusCode, 500);
86103
});
87104

88105
test("'/flags' should return the flags list as JSON", async() => {
@@ -111,19 +128,12 @@ describe("httpServer", { concurrency: 1 }, () => {
111128
});
112129
});
113130

114-
test("'/flags/description/:title' should fail", async() => {
115-
const module = await esmock("../src/http-server/endpoints/flags.js", {
116-
stream: {
117-
pipeline: (_stream, _res, err) => err("fake error")
118-
},
119-
fs: {
120-
createReadStream: () => "foo"
121-
}
122-
});
131+
test("'/flags/description/:title' should fail", async(ctx) => {
132+
ctx.mock.method(stream, "pipeline", (_stream, _res, err) => err("fake error"));
123133
const logs = [];
124134
console.error = (data) => logs.push(data);
125135

126-
await module.get({ params: { title: "hasWarnings" } }, ({ writeHead: () => true }));
136+
await flagsEndpoint.get({ params: { title: "hasWarnings" } }, ({ writeHead: () => true }));
127137
assert.deepEqual(logs, ["fake error"]);
128138
});
129139

@@ -312,30 +322,25 @@ describe("httpServer", { concurrency: 1 }, () => {
312322

313323
describe("httpServer without options", () => {
314324
let httpServer;
315-
let opened = false;
325+
let spawnOpen;
316326
// We want to disable WS
317327
process.env.NODE_ENV = "test";
318328

319329
before(async() => {
320-
const module = await esmock("../src/http-server/index.js", {
321-
open: () => (opened = true)
322-
});
323-
324-
httpServer = module.buildServer(JSON_PATH);
330+
spawnOpen = mock.method(BROWSER, "open", () => void 0);
331+
httpServer = buildServer(JSON_PATH);
325332
await once(httpServer.server, "listening");
326333
enableDestroy(httpServer.server);
327334
});
328335

329336
after(async() => {
330337
httpServer.server.destroy();
338+
spawnOpen.mock.restore();
331339
});
332340

333-
test("should listen on random port", () => {
341+
test("should listen on random port and call childProcess.spawn method ('open' pkg) to open link", async() => {
334342
assert.ok(httpServer.server.address().port > 0);
335-
});
336-
337-
test("should have openLink to true", () => {
338-
assert.equal(opened, true);
343+
assert.strictEqual(spawnOpen.mock.callCount(), 1);
339344
});
340345
});
341346

0 commit comments

Comments
 (0)