Skip to content

Commit

Permalink
mocha test plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
zoeyTM committed Aug 14, 2024
1 parent 9460fd6 commit fa61d86
Show file tree
Hide file tree
Showing 19 changed files with 372 additions and 1 deletion.
76 changes: 76 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 12 additions & 1 deletion v-next/example-project/hardhat.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
HardhatUserConfig,
} from "@ignored/hardhat-vnext/config";
import HardhatNodeTestRunner from "@ignored/hardhat-vnext-node-test-runner";
import HardhatMochaTestRunner from "@ignored/hardhat-vnext-mocha-test-runner";

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

Expand Down Expand Up @@ -102,8 +103,18 @@ const config: HardhatUserConfig = {
exampleEmptySubtask,
greeting,
],
plugins: [pluginExample, HardhatNodeTestRunner],
plugins: [
pluginExample,
HardhatMochaTestRunner,
// if testing node plugin, use the following line instead
// HardhatNodeTestRunner,
],
privateKey: configVariable("privateKey"),
paths: {
tests: "test/mocha",
// if testing node plugin, use the following line instead
// tests: "test/node",
},
};

export default config;
3 changes: 3 additions & 0 deletions v-next/example-project/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@
},
"devDependencies": {
"@ignored/hardhat-vnext": "workspace:^3.0.0-next.3",
"@ignored/hardhat-vnext-mocha-test-runner": "workspace:^3.0.0-next.2",
"@ignored/hardhat-vnext-node-test-runner": "workspace:^3.0.0-next.2",
"@types/mocha": ">=9.1.0",
"@types/node": "^20.14.9",
"mocha": "^10.0.0",
"prettier": "3.2.5",
"typescript": "~5.5.0"
},
Expand Down
8 changes: 8 additions & 0 deletions v-next/example-project/test/mocha/mocha-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import assert from "node:assert/strict";
import { describe, it } from "mocha";

describe("Mocha test", () => {
it("should work", () => {
assert.equal(1 + 1, 2);
});
});
16 changes: 16 additions & 0 deletions v-next/example-project/test/mocha/other-mocha-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import assert from "node:assert/strict";
import { describe, it } from "mocha";

// import hre from "@ignored/hardhat-vnext";

// describe("Other mocha test", () => {
// it("should have the example task", () => {
// assert.ok(hre.tasks.getTask("example"));
// });
// });

describe("Other mocha test", () => {
it("should have the example task", () => {
assert.ok(true);
});
});
File renamed without changes.
7 changes: 7 additions & 0 deletions v-next/hardhat-errors/src/descriptors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -492,5 +492,12 @@ Please double check your script's path.`,
Please check Hardhat's output for more details.`,
},
TEST_TASK_ESM_TESTS_RUN_TWICE: {
number: 602,
messageTemplate: `Your project uses ESM and you've programmatically run your tests twice. This is not supported yet.`,
websiteTitle: "Running tests twice in an ESM project",
websiteDescription:
'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.',
},
},
} as const;
3 changes: 3 additions & 0 deletions v-next/hardhat-mocha-test-runner/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { createConfig } = require("../../config-v-next/eslint.cjs");

module.exports = createConfig(__filename);
5 changes: 5 additions & 0 deletions v-next/hardhat-mocha-test-runner/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Node modules
/node_modules

# Compilation output
/dist
3 changes: 3 additions & 0 deletions v-next/hardhat-mocha-test-runner/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/node_modules
/dist
CHANGELOG.md
9 changes: 9 additions & 0 deletions v-next/hardhat-mocha-test-runner/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2024 Nomic Foundation

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.
3 changes: 3 additions & 0 deletions v-next/hardhat-mocha-test-runner/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Hardhat's `mocha` test runner

This package includes Hardhat's `mocha` test runner.
66 changes: 66 additions & 0 deletions v-next/hardhat-mocha-test-runner/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
{
"name": "@ignored/hardhat-vnext-mocha-test-runner",
"version": "3.0.0-next.2",
"description": "A mocha test runner",
"homepage": "https://github.com/nomicfoundation/hardhat/tree/v-next/v-next/hardhat-mocha-test-runner",
"repository": {
"type": "git",
"url": "https://github.com/NomicFoundation/hardhat",
"directory": "v-next/hardhat-mocha-test-runner"
},
"author": "Nomic Foundation",
"license": "MIT",
"type": "module",
"exports": {
".": "./dist/src/index.js"
},
"keywords": [
"ethereum",
"smart-contracts",
"hardhat"
],
"scripts": {
"lint": "pnpm prettier --check && pnpm eslint",
"lint:fix": "pnpm prettier --write && pnpm eslint --fix",
"eslint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
"prettier": "prettier \"**/*.{ts,js,md,json}\"",
"test": "node --import tsx/esm --test --test-reporter=@ignored/hardhat-vnext-node-test-reporter \"test/*.ts\" \"test/!(fixture-projects|helpers)/**/*.ts\"",
"test:only": "node --import tsx/esm --test --test-only --test-reporter=@ignored/hardhat-vnext-node-test-reporter \"test/*.ts\" \"test/!(fixture-projects|helpers)/**/*.ts\"",
"pretest": "pnpm build",
"build": "tsc --build .",
"prepublishOnly": "pnpm build",
"clean": "rimraf dist"
},
"files": [
"dist/src/",
"src/",
"CHANGELOG.md",
"LICENSE",
"README.md"
],
"devDependencies": {
"@eslint-community/eslint-plugin-eslint-comments": "^4.3.0",
"@nomicfoundation/hardhat-test-utils": "workspace:^",
"@types/mocha": ">=9.1.0",
"@types/node": "^20.14.9",
"@typescript-eslint/eslint-plugin": "^7.7.1",
"@typescript-eslint/parser": "^7.7.1",
"eslint": "8.57.0",
"eslint-config-prettier": "9.1.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "2.29.1",
"eslint-plugin-no-only-tests": "3.1.0",
"expect-type": "^0.19.0",
"prettier": "3.2.5",
"rimraf": "^5.0.5",
"typescript": "~5.5.0",
"typescript-eslint": "7.7.1"
},
"dependencies": {
"@ignored/hardhat-vnext-core": "workspace:^3.0.0-next.2",
"@ignored/hardhat-vnext-errors": "workspace:^3.0.0-next.2",
"@ignored/hardhat-vnext-utils": "workspace:^3.0.0-next.2",
"mocha": "^10.0.0",
"tsx": "^4.11.0"
}
}
19 changes: 19 additions & 0 deletions v-next/hardhat-mocha-test-runner/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { HardhatPlugin } from "@ignored/hardhat-vnext-core/types/plugins";

import { task } from "@ignored/hardhat-vnext-core/config";

const hardhatPlugin: HardhatPlugin = {
id: "test",
tasks: [
task("test", "Runs tests using the Mocha test runner")
.addVariadicArgument({
name: "testFiles",
description: "An optional list of files to test",
defaultValue: [],
})
.setAction(import.meta.resolve("./task-action.js"))
.build(),
],
};

export default hardhatPlugin;
109 changes: 109 additions & 0 deletions v-next/hardhat-mocha-test-runner/src/task-action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import type { HardhatConfig } from "@ignored/hardhat-vnext-core/types/config";
import type { NewTaskActionFunction } from "@ignored/hardhat-vnext-core/types/tasks";
import type { MochaOptions } from "mocha";

import { resolve as pathResolve } from "node:path";

import { HardhatError } from "@ignored/hardhat-vnext-errors";
import { findUp, getAllFilesMatching } from "@ignored/hardhat-vnext-utils/fs";
import { readClosestPackageJson } from "@ignored/hardhat-vnext-utils/package";

interface TestActionArguments {
testFiles: string[];
}

function isTypescriptFile(path: string): boolean {
return /\.(ts|cts|mts)$/i.test(path);
}

function isJavascriptFile(path: string): boolean {
return /\.(js|cjs|mjs)$/i.test(path);
}

async function getTestFiles(
testFiles: string[],
config: HardhatConfig,
): Promise<string[]> {
if (testFiles.length !== 0) {
const testFilesAbsolutePaths = testFiles.map((x) =>
pathResolve(process.cwd(), x),
);

return testFilesAbsolutePaths;
}

return getAllFilesMatching(
config.paths.tests,
(f) => isJavascriptFile(f) || isTypescriptFile(f),
);
}

async function hasTypescriptConfig(): Promise<boolean> {
const hhConfig = await findUp("hardhat.config.ts");

return hhConfig !== undefined;
}

let testsAlreadyRun = false;
const testWithHardhat: NewTaskActionFunction<TestActionArguments> = async (
{ testFiles },
hre,
) => {
const files = await getTestFiles(testFiles, hre.config);

// the second check is needed for the case of a user having a hardhat.config.ts file
// but all their test files are js files. probably an edge case, but we should handle it
if (files.some((f) => isTypescriptFile(f)) || (await hasTypescriptConfig())) {
try {
import.meta.resolve("typescript");
} catch {
throw new HardhatError(
HardhatError.ERRORS.GENERAL.TYPESCRIPT_NOT_INSTALLED,
);
}

try {
import.meta.resolve("tsx");
} catch {
throw new HardhatError(HardhatError.ERRORS.GENERAL.TSX_NOT_INSTALLED);
}

process.env.NODE_OPTIONS = "--import tsx";
}

const { default: Mocha } = await import("mocha");

const mochaConfig: MochaOptions = { ...hre.config.mocha };

const mocha = new Mocha(mochaConfig);

files.forEach((file) => mocha.addFile(file));

// if the project is of type "module" or if there's some ESM test file,
// we call loadFilesAsync to enable Mocha's ESM support
const projectPackageJson = await readClosestPackageJson(import.meta.url);
const isTypeModule = projectPackageJson.type === "module";
const hasEsmTest = files.some((file) => file.endsWith(".mjs"));

if (isTypeModule || hasEsmTest) {
// Because of the way the ESM cache works, loadFilesAsync doesn't work
// correctly if used twice within the same process, so we throw an error
// in that case
if (testsAlreadyRun) {
throw new HardhatError(
HardhatError.ERRORS.BUILTIN_TASKS.TEST_TASK_ESM_TESTS_RUN_TWICE,
);
}
testsAlreadyRun = true;

// This instructs Mocha to use the more verbose file loading infrastructure
// which supports both ESM and CJS
await mocha.loadFilesAsync();
}

await new Promise<number>((resolve) => {
mocha.run(resolve);
});
};

export default testWithHardhat;
Loading

0 comments on commit fa61d86

Please sign in to comment.