Skip to content

Commit fa61d86

Browse files
committed
mocha test plugin
1 parent 9460fd6 commit fa61d86

19 files changed

+372
-1
lines changed

pnpm-lock.yaml

+76
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

v-next/example-project/hardhat.config.ts

+12-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
HardhatUserConfig,
99
} from "@ignored/hardhat-vnext/config";
1010
import HardhatNodeTestRunner from "@ignored/hardhat-vnext-node-test-runner";
11+
import HardhatMochaTestRunner from "@ignored/hardhat-vnext-mocha-test-runner";
1112

1213
const exampleEmptyTask = emptyTask("empty", "An example empty task").build();
1314

@@ -102,8 +103,18 @@ const config: HardhatUserConfig = {
102103
exampleEmptySubtask,
103104
greeting,
104105
],
105-
plugins: [pluginExample, HardhatNodeTestRunner],
106+
plugins: [
107+
pluginExample,
108+
HardhatMochaTestRunner,
109+
// if testing node plugin, use the following line instead
110+
// HardhatNodeTestRunner,
111+
],
106112
privateKey: configVariable("privateKey"),
113+
paths: {
114+
tests: "test/mocha",
115+
// if testing node plugin, use the following line instead
116+
// tests: "test/node",
117+
},
107118
};
108119

109120
export default config;

v-next/example-project/package.json

+3
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,11 @@
2222
},
2323
"devDependencies": {
2424
"@ignored/hardhat-vnext": "workspace:^3.0.0-next.3",
25+
"@ignored/hardhat-vnext-mocha-test-runner": "workspace:^3.0.0-next.2",
2526
"@ignored/hardhat-vnext-node-test-runner": "workspace:^3.0.0-next.2",
27+
"@types/mocha": ">=9.1.0",
2628
"@types/node": "^20.14.9",
29+
"mocha": "^10.0.0",
2730
"prettier": "3.2.5",
2831
"typescript": "~5.5.0"
2932
},
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import assert from "node:assert/strict";
2+
import { describe, it } from "mocha";
3+
4+
describe("Mocha test", () => {
5+
it("should work", () => {
6+
assert.equal(1 + 1, 2);
7+
});
8+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import assert from "node:assert/strict";
2+
import { describe, it } from "mocha";
3+
4+
// import hre from "@ignored/hardhat-vnext";
5+
6+
// describe("Other mocha test", () => {
7+
// it("should have the example task", () => {
8+
// assert.ok(hre.tasks.getTask("example"));
9+
// });
10+
// });
11+
12+
describe("Other mocha test", () => {
13+
it("should have the example task", () => {
14+
assert.ok(true);
15+
});
16+
});

v-next/hardhat-errors/src/descriptors.ts

+7
Original file line numberDiff line numberDiff line change
@@ -492,5 +492,12 @@ Please double check your script's path.`,
492492
493493
Please check Hardhat's output for more details.`,
494494
},
495+
TEST_TASK_ESM_TESTS_RUN_TWICE: {
496+
number: 602,
497+
messageTemplate: `Your project uses ESM and you've programmatically run your tests twice. This is not supported yet.`,
498+
websiteTitle: "Running tests twice in an ESM project",
499+
websiteDescription:
500+
'You have run your tests twice programmatically and your project is an ESM project (you have `"type": "module"` in your `package.json`, or some of your files have the `.mjs` extension). This is not supported by Mocha yet.',
501+
},
495502
},
496503
} as const;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const { createConfig } = require("../../config-v-next/eslint.cjs");
2+
3+
module.exports = createConfig(__filename);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Node modules
2+
/node_modules
3+
4+
# Compilation output
5+
/dist
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/node_modules
2+
/dist
3+
CHANGELOG.md
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
MIT License
2+
3+
Copyright (c) 2024 Nomic Foundation
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Hardhat's `mocha` test runner
2+
3+
This package includes Hardhat's `mocha` test runner.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
{
2+
"name": "@ignored/hardhat-vnext-mocha-test-runner",
3+
"version": "3.0.0-next.2",
4+
"description": "A mocha test runner",
5+
"homepage": "https://github.com/nomicfoundation/hardhat/tree/v-next/v-next/hardhat-mocha-test-runner",
6+
"repository": {
7+
"type": "git",
8+
"url": "https://github.com/NomicFoundation/hardhat",
9+
"directory": "v-next/hardhat-mocha-test-runner"
10+
},
11+
"author": "Nomic Foundation",
12+
"license": "MIT",
13+
"type": "module",
14+
"exports": {
15+
".": "./dist/src/index.js"
16+
},
17+
"keywords": [
18+
"ethereum",
19+
"smart-contracts",
20+
"hardhat"
21+
],
22+
"scripts": {
23+
"lint": "pnpm prettier --check && pnpm eslint",
24+
"lint:fix": "pnpm prettier --write && pnpm eslint --fix",
25+
"eslint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
26+
"prettier": "prettier \"**/*.{ts,js,md,json}\"",
27+
"test": "node --import tsx/esm --test --test-reporter=@ignored/hardhat-vnext-node-test-reporter \"test/*.ts\" \"test/!(fixture-projects|helpers)/**/*.ts\"",
28+
"test:only": "node --import tsx/esm --test --test-only --test-reporter=@ignored/hardhat-vnext-node-test-reporter \"test/*.ts\" \"test/!(fixture-projects|helpers)/**/*.ts\"",
29+
"pretest": "pnpm build",
30+
"build": "tsc --build .",
31+
"prepublishOnly": "pnpm build",
32+
"clean": "rimraf dist"
33+
},
34+
"files": [
35+
"dist/src/",
36+
"src/",
37+
"CHANGELOG.md",
38+
"LICENSE",
39+
"README.md"
40+
],
41+
"devDependencies": {
42+
"@eslint-community/eslint-plugin-eslint-comments": "^4.3.0",
43+
"@nomicfoundation/hardhat-test-utils": "workspace:^",
44+
"@types/mocha": ">=9.1.0",
45+
"@types/node": "^20.14.9",
46+
"@typescript-eslint/eslint-plugin": "^7.7.1",
47+
"@typescript-eslint/parser": "^7.7.1",
48+
"eslint": "8.57.0",
49+
"eslint-config-prettier": "9.1.0",
50+
"eslint-import-resolver-typescript": "^3.6.1",
51+
"eslint-plugin-import": "2.29.1",
52+
"eslint-plugin-no-only-tests": "3.1.0",
53+
"expect-type": "^0.19.0",
54+
"prettier": "3.2.5",
55+
"rimraf": "^5.0.5",
56+
"typescript": "~5.5.0",
57+
"typescript-eslint": "7.7.1"
58+
},
59+
"dependencies": {
60+
"@ignored/hardhat-vnext-core": "workspace:^3.0.0-next.2",
61+
"@ignored/hardhat-vnext-errors": "workspace:^3.0.0-next.2",
62+
"@ignored/hardhat-vnext-utils": "workspace:^3.0.0-next.2",
63+
"mocha": "^10.0.0",
64+
"tsx": "^4.11.0"
65+
}
66+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import type { HardhatPlugin } from "@ignored/hardhat-vnext-core/types/plugins";
2+
3+
import { task } from "@ignored/hardhat-vnext-core/config";
4+
5+
const hardhatPlugin: HardhatPlugin = {
6+
id: "test",
7+
tasks: [
8+
task("test", "Runs tests using the Mocha test runner")
9+
.addVariadicArgument({
10+
name: "testFiles",
11+
description: "An optional list of files to test",
12+
defaultValue: [],
13+
})
14+
.setAction(import.meta.resolve("./task-action.js"))
15+
.build(),
16+
],
17+
};
18+
19+
export default hardhatPlugin;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import type { HardhatConfig } from "@ignored/hardhat-vnext-core/types/config";
2+
import type { NewTaskActionFunction } from "@ignored/hardhat-vnext-core/types/tasks";
3+
import type { MochaOptions } from "mocha";
4+
5+
import { resolve as pathResolve } from "node:path";
6+
7+
import { HardhatError } from "@ignored/hardhat-vnext-errors";
8+
import { findUp, getAllFilesMatching } from "@ignored/hardhat-vnext-utils/fs";
9+
import { readClosestPackageJson } from "@ignored/hardhat-vnext-utils/package";
10+
11+
interface TestActionArguments {
12+
testFiles: string[];
13+
}
14+
15+
function isTypescriptFile(path: string): boolean {
16+
return /\.(ts|cts|mts)$/i.test(path);
17+
}
18+
19+
function isJavascriptFile(path: string): boolean {
20+
return /\.(js|cjs|mjs)$/i.test(path);
21+
}
22+
23+
async function getTestFiles(
24+
testFiles: string[],
25+
config: HardhatConfig,
26+
): Promise<string[]> {
27+
if (testFiles.length !== 0) {
28+
const testFilesAbsolutePaths = testFiles.map((x) =>
29+
pathResolve(process.cwd(), x),
30+
);
31+
32+
return testFilesAbsolutePaths;
33+
}
34+
35+
return getAllFilesMatching(
36+
config.paths.tests,
37+
(f) => isJavascriptFile(f) || isTypescriptFile(f),
38+
);
39+
}
40+
41+
async function hasTypescriptConfig(): Promise<boolean> {
42+
const hhConfig = await findUp("hardhat.config.ts");
43+
44+
return hhConfig !== undefined;
45+
}
46+
47+
let testsAlreadyRun = false;
48+
const testWithHardhat: NewTaskActionFunction<TestActionArguments> = async (
49+
{ testFiles },
50+
hre,
51+
) => {
52+
const files = await getTestFiles(testFiles, hre.config);
53+
54+
// the second check is needed for the case of a user having a hardhat.config.ts file
55+
// but all their test files are js files. probably an edge case, but we should handle it
56+
if (files.some((f) => isTypescriptFile(f)) || (await hasTypescriptConfig())) {
57+
try {
58+
import.meta.resolve("typescript");
59+
} catch {
60+
throw new HardhatError(
61+
HardhatError.ERRORS.GENERAL.TYPESCRIPT_NOT_INSTALLED,
62+
);
63+
}
64+
65+
try {
66+
import.meta.resolve("tsx");
67+
} catch {
68+
throw new HardhatError(HardhatError.ERRORS.GENERAL.TSX_NOT_INSTALLED);
69+
}
70+
71+
process.env.NODE_OPTIONS = "--import tsx";
72+
}
73+
74+
const { default: Mocha } = await import("mocha");
75+
76+
const mochaConfig: MochaOptions = { ...hre.config.mocha };
77+
78+
const mocha = new Mocha(mochaConfig);
79+
80+
files.forEach((file) => mocha.addFile(file));
81+
82+
// if the project is of type "module" or if there's some ESM test file,
83+
// we call loadFilesAsync to enable Mocha's ESM support
84+
const projectPackageJson = await readClosestPackageJson(import.meta.url);
85+
const isTypeModule = projectPackageJson.type === "module";
86+
const hasEsmTest = files.some((file) => file.endsWith(".mjs"));
87+
88+
if (isTypeModule || hasEsmTest) {
89+
// Because of the way the ESM cache works, loadFilesAsync doesn't work
90+
// correctly if used twice within the same process, so we throw an error
91+
// in that case
92+
if (testsAlreadyRun) {
93+
throw new HardhatError(
94+
HardhatError.ERRORS.BUILTIN_TASKS.TEST_TASK_ESM_TESTS_RUN_TWICE,
95+
);
96+
}
97+
testsAlreadyRun = true;
98+
99+
// This instructs Mocha to use the more verbose file loading infrastructure
100+
// which supports both ESM and CJS
101+
await mocha.loadFilesAsync();
102+
}
103+
104+
await new Promise<number>((resolve) => {
105+
mocha.run(resolve);
106+
});
107+
};
108+
109+
export default testWithHardhat;

0 commit comments

Comments
 (0)