diff --git a/.github/workflows/verify-node.yml b/.github/workflows/verify-node.yml index 8be272e5de..d61a4a6daa 100644 --- a/.github/workflows/verify-node.yml +++ b/.github/workflows/verify-node.yml @@ -56,9 +56,6 @@ jobs: - name: Test run: npm run test:node - env: - # Node 22.18+ native type stripping preempts ts-node. Remove when mocha is replaced with node:test. - NODE_OPTIONS: '--no-experimental-strip-types' verify-windows: timeout-minutes: 30 @@ -98,6 +95,3 @@ jobs: - name: Test run: npm run test:node - env: - # Node 22.18+ native type stripping preempts ts-node. Remove when mocha is replaced with node:test. - NODE_OPTIONS: '--no-experimental-strip-types' diff --git a/package-lock.json b/package-lock.json index be4e6c73b7..9045bc8bea 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,10 +22,9 @@ "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-terser": "^0.4.4", "@rollup/plugin-typescript": "^11.1.5", - "@types/chai": "^4.2.22", "@types/fs-extra": "^11.0.4", - "@types/mocha": "^10.0.1", "@types/node": "*", + "@types/react": ">=16", "@typescript-eslint/eslint-plugin": "^5.3.0", "@typescript-eslint/parser": "^5.59.1", "alex": "^11.0.0", @@ -38,13 +37,11 @@ "hanbi": "^1.0.1", "husky": "^9.1.7", "lint-staged": "^15.2.11", - "mocha": "^10.8.2", "nanocolors": "^0.2.1", "prettier": "^2.4.1", "prettier-plugin-package": "^1.3.0", "rimraf": "^4.4.1", "rollup": "^4.4.0", - "ts-node": "^10.4.0", "typescript": "~5.0.4", "wireit": "^0.14.2" }, @@ -2231,30 +2228,6 @@ "prettier": "^2.7.1" } }, - "node_modules/@cspotcode/source-map-support": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", - "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "0.3.9" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", - "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" - } - }, "node_modules/@eggjs/yauzl": { "version": "2.11.0", "resolved": "https://registry.npmjs.org/@eggjs/yauzl/-/yauzl-2.11.0.tgz", @@ -5344,26 +5317,6 @@ "node": ">=6" } }, - "node_modules/@testing-library/dom": { - "version": "10.4.1", - "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz", - "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==", - "license": "MIT", - "peer": true, - "dependencies": { - "@babel/code-frame": "^7.10.4", - "@babel/runtime": "^7.12.5", - "@types/aria-query": "^5.0.1", - "aria-query": "5.3.0", - "dom-accessibility-api": "^0.5.9", - "lz-string": "^1.5.0", - "picocolors": "1.1.1", - "pretty-format": "^27.0.2" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/@testing-library/jest-dom": { "version": "6.9.1", "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz", @@ -5418,34 +5371,6 @@ "node": ">=10.13.0" } }, - "node_modules/@tsconfig/node10": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", - "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tsconfig/node12": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", - "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tsconfig/node14": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", - "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tsconfig/node16": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", - "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/accepts": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/@types/accepts/-/accepts-1.3.5.tgz", @@ -5464,13 +5389,6 @@ "@types/estree": "*" } }, - "node_modules/@types/aria-query": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", - "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", - "license": "MIT", - "peer": true - }, "node_modules/@types/babel__code-frame": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/@types/babel__code-frame/-/babel__code-frame-7.0.3.tgz", @@ -5481,7 +5399,7 @@ "version": "7.20.1", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.1.tgz", "integrity": "sha512-aACu/U/omhdk15O4Nfb+fHgH/z3QsfQzpnvRZhYhThms83ZnAOZz7zZAWO7mn2yyNQaA4xTO8GLK3uqFU4bYYw==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.20.7", @@ -5495,7 +5413,7 @@ "version": "7.6.4", "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.4.tgz", "integrity": "sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "@babel/types": "^7.0.0" @@ -5505,7 +5423,7 @@ "version": "7.4.1", "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.1.0", @@ -5516,7 +5434,7 @@ "version": "7.20.1", "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.1.tgz", "integrity": "sha512-MitHFXnhtgwsGZWtT68URpOvLN4EREih1u3QtQiN4VdAxWKRVvGCSvw/Qth0M0Qq3pJpnGOu5JaM/ydK7OGbqg==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "@babel/types": "^7.20.7" @@ -5971,9 +5889,9 @@ } }, "node_modules/@types/mocha": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.1.tgz", - "integrity": "sha512-/fvYntiO1GeICvqbQ3doGDIP97vWmvFt83GKguJ6prmQM2iXZfFcq6YE8KteFyRtX2/h5Hf91BYvPodJKFYv5Q==", + "version": "10.0.10", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.10.tgz", + "integrity": "sha512-xPyYSz1cMPnJQhl0CLMH68j3gprKZaTjG3s5Vi+fDgx+uhG9NOXwbVt52eFS8ECyXhyKcjDLCBEqBExKuiZb7Q==", "dev": true, "license": "MIT" }, @@ -6070,12 +5988,11 @@ "license": "MIT" }, "node_modules/@types/react": { - "version": "19.2.14", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", - "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", + "version": "19.2.15", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.15.tgz", + "integrity": "sha512-eRwcGNHve+E8qtEQSSRl6urh+rFop4v8gm6O8rGv25CodbvFdLjA1vVQ1KkiFE0w0UPOnb8tDiFKL5lp0rtY5Q==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "csstype": "^3.2.2" } @@ -7075,16 +6992,6 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, - "node_modules/acorn-walk": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", - "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/agent-base": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", @@ -8253,13 +8160,6 @@ "safe-buffer": "~5.2.0" } }, - "node_modules/arg": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", - "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", - "dev": true, - "license": "MIT" - }, "node_modules/argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", @@ -9672,19 +9572,19 @@ } }, "node_modules/chai": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", - "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.5.0.tgz", + "integrity": "sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw==", "dev": true, "license": "MIT", "dependencies": { "assertion-error": "^1.1.0", - "check-error": "^1.0.2", - "deep-eql": "^4.1.2", - "get-func-name": "^2.0.0", - "loupe": "^2.3.1", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", "pathval": "^1.1.1", - "type-detect": "^4.0.5" + "type-detect": "^4.1.0" }, "engines": { "node": ">=4" @@ -9866,11 +9766,14 @@ "license": "MIT" }, "node_modules/check-error": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz", - "integrity": "sha512-BrgHpW9NURQgzoNyjfq0Wu6VFO6D7IZEmJNdtgNqpzGG8RuNFHt2jQxWlAs4HMe119chBnv+34syEZtc6IhLtA==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", "dev": true, "license": "MIT", + "dependencies": { + "get-func-name": "^2.0.2" + }, "engines": { "node": "*" } @@ -11306,13 +11209,6 @@ "safe-buffer": "~5.2.0" } }, - "node_modules/create-require": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", - "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", - "dev": true, - "license": "MIT" - }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -11564,8 +11460,7 @@ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/cuss": { "version": "2.2.0", @@ -11708,9 +11603,9 @@ } }, "node_modules/deep-eql": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", - "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.4.tgz", + "integrity": "sha512-SUwdGfqdKOwxCPeVYjwSyRpJ7Z+fhpwIAtmCUdZIWZ/YP5R9WAsyuSgpLVDi9bjWoN2LXHNss/dk3urXtdQxGg==", "dev": true, "license": "MIT", "dependencies": { @@ -12068,13 +11963,6 @@ "integrity": "sha512-LLBi6pEqS6Do3EKQ3J0NqHWV5hhb78Pi8vvESYwyOy2c31ZEZVdtitdzsQsKb7878PEERhzUk0ftqGhG6Mz+pQ==", "license": "MIT" }, - "node_modules/dom-accessibility-api": { - "version": "0.5.16", - "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", - "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", - "license": "MIT", - "peer": true - }, "node_modules/dom-serializer": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz", @@ -14587,9 +14475,9 @@ } }, "node_modules/get-func-name": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz", - "integrity": "sha512-Hm0ixYtaSZ/V7C8FJrtZIuBBI+iSgL+1Aq82zSu8VQNB4S3Gk8e7Qs3VwBDJAhmRZcFqkl3tQu36g/Foh5I5ig==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", "dev": true, "license": "MIT", "engines": { @@ -14972,9 +14860,9 @@ "integrity": "sha512-/chXRp4WpL47I+HX1vCCdSbEXAljEG2FBMmgO7Am0bYsqgnEjreeWzUdX1onXqwZtcfgxbCg5WtEYYvuZ5muBg==" }, "node_modules/hanbi": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/hanbi/-/hanbi-1.0.1.tgz", - "integrity": "sha512-ygE4dxg+khS7BZBZTVqaaq+X3oCQX6q4Z2LvNzRpPdZLmzbmL7xu6KCdjWoRiRlYfyZN9R+gMztf4MftiCH0Mw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/hanbi/-/hanbi-1.1.0.tgz", + "integrity": "sha512-4lCBCYshw5ojLZuPmQ4C1wtGvp5CKqMm8JksLBVfMNA4OvA6XpNZ/OZXaBkC+ZfAPPX5McqwX9uBksDt2PUDfQ==", "dev": true, "license": "MIT" }, @@ -19663,13 +19551,13 @@ } }, "node_modules/loupe": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", - "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", "dev": true, "license": "MIT", "dependencies": { - "get-func-name": "^2.0.0" + "get-func-name": "^2.0.1" } }, "node_modules/lower-case": { @@ -19709,16 +19597,6 @@ "node": "*" } }, - "node_modules/lz-string": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", - "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", - "license": "MIT", - "peer": true, - "bin": { - "lz-string": "bin/bin.js" - } - }, "node_modules/magic-string": { "version": "0.30.17", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz", @@ -19752,13 +19630,6 @@ "semver": "bin/semver.js" } }, - "node_modules/make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true, - "license": "ISC" - }, "node_modules/make-synchronized": { "version": "0.8.0", "resolved": "https://registry.npmjs.org/make-synchronized/-/make-synchronized-0.8.0.tgz", @@ -24208,7 +24079,7 @@ "version": "2.8.8", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", - "devOptional": true, + "dev": true, "license": "MIT", "bin": { "prettier": "bin-prettier.js" @@ -24259,34 +24130,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/pretty-format": { - "version": "27.5.1", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", - "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "ansi-regex": "^5.0.1", - "ansi-styles": "^5.0.0", - "react-is": "^17.0.1" - }, - "engines": { - "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" - } - }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, "node_modules/pretty-ms": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-0.2.2.tgz", @@ -25026,13 +24869,6 @@ "react": "^19.2.4" } }, - "node_modules/react-is": { - "version": "17.0.2", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", - "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", - "license": "MIT", - "peer": true - }, "node_modules/read-package-json-fast": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/read-package-json-fast/-/read-package-json-fast-3.0.2.tgz", @@ -31312,60 +31148,6 @@ "node": ">=6.10" } }, - "node_modules/ts-node": { - "version": "10.9.1", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", - "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cspotcode/source-map-support": "^0.8.0", - "@tsconfig/node10": "^1.0.7", - "@tsconfig/node12": "^1.0.7", - "@tsconfig/node14": "^1.0.0", - "@tsconfig/node16": "^1.0.2", - "acorn": "^8.4.1", - "acorn-walk": "^8.1.1", - "arg": "^4.1.0", - "create-require": "^1.1.0", - "diff": "^4.0.1", - "make-error": "^1.1.1", - "v8-compile-cache-lib": "^3.0.1", - "yn": "3.1.1" - }, - "bin": { - "ts-node": "dist/bin.js", - "ts-node-cwd": "dist/bin-cwd.js", - "ts-node-esm": "dist/bin-esm.js", - "ts-node-script": "dist/bin-script.js", - "ts-node-transpile-only": "dist/bin-transpile.js", - "ts-script": "dist/bin-script-deprecated.js" - }, - "peerDependencies": { - "@swc/core": ">=1.2.50", - "@swc/wasm": ">=1.2.50", - "@types/node": "*", - "typescript": ">=2.7" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "@swc/wasm": { - "optional": true - } - } - }, - "node_modules/ts-node/node_modules/diff": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", - "integrity": "sha512-X07nttJQkwkfKfvTPG/KSnE2OMdcUCao6+eXF3wmnIQRn2aPAHH3VxDbDOdegkd6JbPsXqShpvEOHfAT+nCNwQ==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.3.1" - } - }, "node_modules/tslib": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.0.tgz", @@ -31439,9 +31221,9 @@ } }, "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.1.0.tgz", + "integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==", "dev": true, "license": "MIT", "engines": { @@ -31565,7 +31347,7 @@ "version": "5.0.4", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.4.tgz", "integrity": "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==", - "devOptional": true, + "dev": true, "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", @@ -32445,13 +32227,6 @@ "node": ">=8" } }, - "node_modules/v8-compile-cache-lib": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", - "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", - "dev": true, - "license": "MIT" - }, "node_modules/v8-to-istanbul": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.0.tgz", @@ -34118,16 +33893,6 @@ "node": ">= 4.0.0" } }, - "node_modules/yn": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", - "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/yocto-queue": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.0.0.tgz", @@ -34247,7 +34012,7 @@ "puppeteer": "^24.0.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/config-loader": { @@ -34255,7 +34020,7 @@ "version": "0.3.3", "license": "MIT", "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/dev-server": { @@ -34288,7 +34053,7 @@ "puppeteer": "^24.0.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/dev-server-core": { @@ -34326,7 +34091,7 @@ "portfinder": "^1.0.32" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/dev-server-core/node_modules/chokidar": { @@ -34375,7 +34140,7 @@ "preact": "^10.5.9" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/dev-server-esbuild/node_modules/@esbuild/aix-ppc64": { @@ -34831,7 +34596,7 @@ "puppeteer": "^24.0.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/dev-server-import-maps": { @@ -34850,7 +34615,7 @@ "@web/test-runner": "^0.20.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/dev-server-legacy": { @@ -34882,7 +34647,7 @@ "@types/valid-url": "^1.0.3" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/dev-server-polyfill": { @@ -34894,7 +34659,7 @@ "@web/polyfills-loader": "^2.3.1" }, "engines": { - "node": ">=16.0.0" + "node": ">=22.0.0" } }, "packages/dev-server-rollup": { @@ -34919,13 +34684,11 @@ "@types/whatwg-url": "^11.0.0", "@web/test-runner-chrome": "^0.18.0", "@web/test-runner-core": "^0.13.0", - "chai": "^4.2.0", - "mocha": "^10.8.2", "postcss": "^8.5.14", "rollup-plugin-postcss": "^4.0.2" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/dev-server-rollup/node_modules/@rollup/plugin-alias": { @@ -35173,7 +34936,7 @@ "@types/html-minifier-terser": "^7.0.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/polyfills-loader": { @@ -35207,7 +34970,7 @@ "@types/valid-url": "^1.0.3" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/polyfills-loader/node_modules/@webcomponents/scoped-custom-element-registry": { @@ -35226,7 +34989,7 @@ "@types/glob": "^8.1.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/rollup-plugin-copy/node_modules/@types/glob": { @@ -35303,7 +35066,7 @@ "rollup": "^4.4.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/rollup-plugin-html/node_modules/brace-expansion": { @@ -35378,7 +35141,7 @@ "magic-string": "^0.30.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/rollup-plugin-import-meta-assets/node_modules/@rollup/plugin-dynamic-import-vars": { @@ -35463,7 +35226,7 @@ "rollup": "^4.4.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/rollup-plugin-workbox": { @@ -35993,7 +35756,7 @@ "storybook": "^9.1.20" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.0.0" } }, "packages/storybook-builder/node_modules/@esbuild/aix-ppc64": { @@ -37840,7 +37603,7 @@ "storybook": "^9.1.20" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.0.0" } }, "packages/storybook-utils": { @@ -37854,7 +37617,7 @@ "react": "^19.0.0" }, "engines": { - "node": ">=16.0.0" + "node": ">=22.0.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0" @@ -37894,7 +37657,7 @@ "concurrently": "^8.0.1" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-browserstack": { @@ -37913,7 +37676,7 @@ "portfinder": "^1.0.32" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-browserstack/node_modules/internal-ip": { @@ -37962,7 +37725,7 @@ "@web/test-runner-mocha": "^0.9.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-cli": { @@ -37970,7 +37733,7 @@ "version": "0.11.0", "license": "MIT", "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-commands": { @@ -37984,11 +37747,10 @@ "devDependencies": { "@web/test-runner-chrome": "^0.18.0", "@web/test-runner-playwright": "^0.11.0", - "@web/test-runner-webdriver": "^0.9.0", - "mocha": "^10.8.2" + "@web/test-runner-webdriver": "^0.9.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-commands/node_modules/mkdirp": { @@ -38039,7 +37801,7 @@ "portfinder": "^1.0.32" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-core/node_modules/chokidar": { @@ -38176,7 +37938,7 @@ "@types/picomatch": "^2.2.1" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-junit-reporter": { @@ -38194,7 +37956,7 @@ "@web/test-runner-playwright": "^0.11.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-mocha": { @@ -38210,7 +37972,7 @@ "mocha": "^10.8.2" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-module-mocking": { @@ -38226,7 +37988,7 @@ "@web/test-runner-core": "^0.13.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-playwright": { @@ -38243,7 +38005,7 @@ "portfinder": "^1.0.32" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-puppeteer": { @@ -38260,7 +38022,7 @@ "puppeteer-core": "^24.0.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-saucelabs": { @@ -38282,7 +38044,7 @@ "portfinder": "^1.0.32" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-saucelabs/node_modules/@sindresorhus/is": { @@ -38606,7 +38368,7 @@ "selenium-standalone": "^8.0.4" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-visual-regression": { @@ -38626,11 +38388,10 @@ "devDependencies": { "@web/test-runner-chrome": "^0.18.0", "@web/test-runner-playwright": "^0.11.0", - "@web/test-runner-webdriver": "^0.9.0", - "mocha": "^10.8.2" + "@web/test-runner-webdriver": "^0.9.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-visual-regression/node_modules/mkdirp": { @@ -38658,7 +38419,7 @@ "selenium-standalone": "^8.0.4" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0" } }, "packages/test-runner-webdriver/node_modules/@types/node": { diff --git a/package.json b/package.json index d946b63639..46603d584f 100644 --- a/package.json +++ b/package.json @@ -53,10 +53,9 @@ "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-terser": "^0.4.4", "@rollup/plugin-typescript": "^11.1.5", - "@types/chai": "^4.2.22", "@types/fs-extra": "^11.0.4", - "@types/mocha": "^10.0.1", "@types/node": "*", + "@types/react": ">=16", "@typescript-eslint/eslint-plugin": "^5.3.0", "@typescript-eslint/parser": "^5.59.1", "alex": "^11.0.0", @@ -69,13 +68,11 @@ "hanbi": "^1.0.1", "husky": "^9.1.7", "lint-staged": "^15.2.11", - "mocha": "^10.8.2", "nanocolors": "^0.2.1", "prettier": "^2.4.1", "prettier-plugin-package": "^1.3.0", "rimraf": "^4.4.1", "rollup": "^4.4.0", - "ts-node": "^10.4.0", "typescript": "~5.0.4", "wireit": "^0.14.2" }, @@ -92,9 +89,25 @@ "env": { "browser": true, "node": true, - "mocha": true, "es2020": true }, + "overrides": [ + { + "files": [ + "packages/*/test/fixtures/**/*.js", + "packages/*/test/**/fixtures/**/*.js", + "packages/*/test/**/*-test.js", + "packages/*/test-browser/**/*.js", + "packages/*/test-remote/**/*.js", + "packages/*/demo/**/*.js", + "integration/**/tests/**/*.js", + "integration/**/fixtures/**/*.js" + ], + "env": { + "mocha": true + } + } + ], "rules": { "@typescript-eslint/no-non-null-assertion": "off", "@typescript-eslint/explicit-module-boundary-types": "off", @@ -114,11 +127,6 @@ "prettier --write --ignore-path .eslintignore" ] }, - "mocha": { - "loader": "ts-node/esm", - "exit": true, - "retries": 3 - }, "overrides": { "@lion/accordion": "^0.11.1", "@lion/combobox": "^0.11.1", diff --git a/packages/browser-logs/package.json b/packages/browser-logs/package.json index 70752ca0a0..f574a3a2bb 100644 --- a/packages/browser-logs/package.json +++ b/packages/browser-logs/package.json @@ -26,8 +26,8 @@ }, "scripts": { "build": "tsc", - "test:node": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --reporter dot", - "test:watch": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/browser-logs/test/serialize-deserialize.test.ts b/packages/browser-logs/test/serialize-deserialize.test.ts index 5a3232684c..e01cb983a0 100644 --- a/packages/browser-logs/test/serialize-deserialize.test.ts +++ b/packages/browser-logs/test/serialize-deserialize.test.ts @@ -1,16 +1,19 @@ -import { expect } from 'chai'; -import puppeteer, { Browser, Page } from 'puppeteer'; +import assert from 'node:assert/strict'; +import { deepEqual as looseDeepEqual } from 'node:assert'; +import { describe, it, before, after } from 'node:test'; +import { createRequire } from 'node:module'; +import puppeteer from 'puppeteer'; +import type { Browser, Page } from 'puppeteer'; import fs from 'fs'; import path from 'path'; -import { deserialize } from '../src/deserialize.js'; +import { deserialize } from '../dist/deserialize.js'; +const require = createRequire(import.meta.url); const serializeScript = fs.readFileSync(require.resolve('../dist/serialize.js'), 'utf-8'); -const defaultOptions = { browserRootDir: __dirname, cwd: __dirname }; - -describe('serialize deserialize', function () { - this.timeout(10000); +const defaultOptions = { browserRootDir: import.meta.dirname, cwd: import.meta.dirname }; +describe('serialize deserialize', { timeout: 10000 }, () => { let browser: Browser; let page: Page; before(async () => { @@ -29,13 +32,13 @@ describe('serialize deserialize', function () { it('handles strings', async () => { const serialized = await page.evaluate(() => (window as any)._serialize('foo')); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal('foo'); + assert.equal(deserialized, 'foo'); }); it('handles numbers', async () => { const serialized = await page.evaluate(() => (window as any)._serialize(1)); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal(1); + assert.equal(deserialized, 1); }); it('handles Date', async () => { @@ -43,7 +46,7 @@ describe('serialize deserialize', function () { (window as any)._serialize(new Date('2020-07-25T12:00:00.000Z')), ); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal('2020-07-25T12:00:00.000Z'); + assert.equal(deserialized, '2020-07-25T12:00:00.000Z'); }); it('handles Function', async () => { @@ -54,8 +57,8 @@ describe('serialize deserialize', function () { return (window as any)._serialize(foo); }); const deserialized = await deserialize(serialized); - expect(typeof deserialized).to.equal('function'); - expect(deserialized.name).to.equal('foo'); + assert.equal(typeof deserialized, 'function'); + assert.equal(deserialized.name, 'foo'); }); it('handles bound Function', async () => { @@ -66,14 +69,14 @@ describe('serialize deserialize', function () { return (window as any)._serialize(foo.bind(null)); }); const deserialized = await deserialize(serialized); - expect(typeof deserialized).to.equal('function'); - expect(deserialized.name).to.equal('foo'); + assert.equal(typeof deserialized, 'function'); + assert.equal(deserialized.name, 'foo'); }); it('handles Symbol', async () => { const serialized = await page.evaluate(() => (window as any)._serialize(Symbol('foo'))); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal('Symbol(foo)'); + assert.equal(deserialized, 'Symbol(foo)'); }); it('handles arrow functions', async () => { @@ -82,8 +85,8 @@ describe('serialize deserialize', function () { return (window as any)._serialize(foo); }); const deserialized = await deserialize(serialized); - expect(typeof deserialized).to.equal('function'); - expect(deserialized.name).to.equal('foo'); + assert.equal(typeof deserialized, 'function'); + assert.equal(deserialized.name, 'foo'); }); it('handles anonymous arrow functions', async () => { @@ -91,8 +94,8 @@ describe('serialize deserialize', function () { (window as any)._serialize((x: number, y: number) => x * y), ); const deserialized = await deserialize(serialized); - expect(typeof deserialized).to.equal('function'); - expect(deserialized.name).to.equal(''); + assert.equal(typeof deserialized, 'function'); + assert.equal(deserialized.name, ''); }); it('handles Text nodes', async () => { @@ -100,7 +103,7 @@ describe('serialize deserialize', function () { (window as any)._serialize(document.createTextNode('hello world')), ); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal('Text: hello world'); + assert.equal(deserialized, 'Text: hello world'); }); it('handles Comment nodes', async () => { @@ -108,7 +111,7 @@ describe('serialize deserialize', function () { (window as any)._serialize(document.createComment('hello world')), ); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal('Comment: hello world'); + assert.equal(deserialized, 'Comment: hello world'); }); it('handles HTMLElement', async () => { @@ -118,7 +121,7 @@ describe('serialize deserialize', function () { return (window as any)._serialize(element); }); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal('HTMLDivElement:

Hello world

'); + assert.equal(deserialized, 'HTMLDivElement:

Hello world

'); }); it('handles ShadowRoot', async () => { @@ -129,15 +132,15 @@ describe('serialize deserialize', function () { return (window as any)._serialize(element.shadowRoot); }); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal('ShadowRoot:

Hello world

'); + assert.equal(deserialized, 'ShadowRoot:

Hello world

'); }); it('handles RegExp', async () => { const serialized = await page.evaluate(() => (window as any)._serialize(/foo.*?\\/)); const deserialized = await deserialize(serialized); - expect(deserialized instanceof RegExp).to.be.true; - expect(deserialized.source).to.equal('foo.*?\\\\'); - expect(deserialized.flags).to.equal(''); + assert.equal(deserialized instanceof RegExp, true); + assert.equal(deserialized.source, 'foo.*?\\\\'); + assert.equal(deserialized.flags, ''); }); it('handles RegExp with flags', async () => { @@ -145,9 +148,9 @@ describe('serialize deserialize', function () { (window as any)._serialize(new RegExp('foo.*?\\\\', 'g')), ); const deserialized = await deserialize(serialized); - expect(deserialized instanceof RegExp).to.be.true; - expect(deserialized.source).to.equal('foo.*?\\\\'); - expect(deserialized.flags).to.equal('g'); + assert.equal(deserialized instanceof RegExp, true); + assert.equal(deserialized.source, 'foo.*?\\\\'); + assert.equal(deserialized.flags, 'g'); }); it('handles URL', async () => { @@ -155,7 +158,7 @@ describe('serialize deserialize', function () { (window as any)._serialize(new URL('https://www.example.com')), ); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal('https://www.example.com/'); + assert.equal(deserialized, 'https://www.example.com/'); }); it('handles URLSearchparams', async () => { @@ -163,7 +166,7 @@ describe('serialize deserialize', function () { (window as any)._serialize(new URLSearchParams('foo=bar&lorem=ipsum')), ); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal('URLSearchParams: foo=bar&lorem=ipsum'); + assert.equal(deserialized, 'URLSearchParams: foo=bar&lorem=ipsum'); }); it('handles classes', async () => { @@ -175,26 +178,26 @@ describe('serialize deserialize', function () { return (window as any)._serialize(new Foo()); }); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql({ a: 1, b: 2 }); - expect(deserialized.constructor.name).to.equal('Foo'); + looseDeepEqual(deserialized, { a: 1, b: 2 }); + assert.equal(deserialized.constructor.name, 'Foo'); }); it('handles objects', async () => { const serialized = await page.evaluate(() => (window as any)._serialize({ a: 1, b: 2 })); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql({ a: 1, b: 2 }); + looseDeepEqual(deserialized, { a: 1, b: 2 }); }); it('handles arrays', async () => { const serialized = await page.evaluate(() => (window as any)._serialize([1, 2, 3])); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql([1, 2, 3]); + looseDeepEqual(deserialized, [1, 2, 3]); }); it('handles objects', async () => { const serialized = await page.evaluate(() => (window as any)._serialize({ a: 1, b: 2 })); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql({ a: 1, b: 2 }); + looseDeepEqual(deserialized, { a: 1, b: 2 }); }); it('handles objects with methods', async () => { @@ -213,14 +216,14 @@ describe('serialize deserialize', function () { }), ); const deserialized = await deserialize(serialized); - expect(deserialized.foo).to.be.a('function'); - expect(deserialized.foo.name).to.equal('foo'); - expect(deserialized.bar).to.be.a('function'); - expect(deserialized.bar.name).to.equal('bar'); - expect(deserialized.baz).to.be.a('function'); - expect(deserialized.baz.name).to.equal('baz'); - expect(deserialized['my-element']).to.be.a('function'); - expect(deserialized['my-element'].name).to.equal('my-element'); + assert.equal(typeof deserialized.foo, 'function'); + assert.equal(deserialized.foo.name, 'foo'); + assert.equal(typeof deserialized.bar, 'function'); + assert.equal(deserialized.bar.name, 'bar'); + assert.equal(typeof deserialized.baz, 'function'); + assert.equal(deserialized.baz.name, 'baz'); + assert.equal(typeof deserialized['my-element'], 'function'); + assert.equal(deserialized['my-element'].name, 'my-element'); }); it('handles deep objects', async () => { @@ -239,14 +242,14 @@ describe('serialize deserialize', function () { }), ); const deserialized = await deserialize(serialized); - expect(deserialized.myNumber).to.equal(123); - expect(deserialized.myString).to.equal('foo'); - expect(deserialized.myObject.myUrl).to.equal('http://www.example.com/'); - expect(deserialized.myObject.myMethod).to.be.a('function'); - expect(deserialized.myObject.myMethod.name).to.equal('myMethod'); - expect(deserialized.myObject.myRegExp).to.a('RegExp'); - expect(deserialized.myObject.myRegExp.source).to.equal('x'); - expect(deserialized.myArray).to.eql([1, '2']); + assert.equal(deserialized.myNumber, 123); + assert.equal(deserialized.myString, 'foo'); + assert.equal(deserialized.myObject.myUrl, 'http://www.example.com/'); + assert.equal(typeof deserialized.myObject.myMethod, 'function'); + assert.equal(deserialized.myObject.myMethod.name, 'myMethod'); + assert.ok(deserialized.myObject.myRegExp instanceof RegExp); + assert.equal(deserialized.myObject.myRegExp.source, 'x'); + looseDeepEqual(deserialized.myArray, [1, '2']); }); it('handles deep arrays', async () => { @@ -264,17 +267,17 @@ describe('serialize deserialize', function () { ]); }); const deserialized = await deserialize(serialized); - expect(deserialized[0]).to.equal(1); - expect(deserialized[1]).to.equal('2'); - expect(deserialized[2]).to.a('RegExp'); - expect(deserialized[2].source).to.equal('x'); - expect(deserialized[3]).to.equal('http://www.example.com/'); - expect(deserialized[4]).to.equal('Symbol(foo)'); - expect(deserialized[5].a).to.equal(1); - expect(deserialized[5].b).to.equal(2); - expect(deserialized[5].c).to.equal('URLSearchParams: x=y'); - expect(deserialized[5].d).to.eql({ x: 'y' }); - expect(deserialized[5].d.constructor.name).to.equal('Foo'); + assert.equal(deserialized[0], 1); + assert.equal(deserialized[1], '2'); + assert.ok(deserialized[2] instanceof RegExp); + assert.equal(deserialized[2].source, 'x'); + assert.equal(deserialized[3], 'http://www.example.com/'); + assert.equal(deserialized[4], 'Symbol(foo)'); + assert.equal(deserialized[5].a, 1); + assert.equal(deserialized[5].b, 2); + assert.equal(deserialized[5].c, 'URLSearchParams: x=y'); + looseDeepEqual(deserialized[5].d, { x: 'y' }); + assert.equal(deserialized[5].d.constructor.name, 'Foo'); }); it('handles circular references', async () => { @@ -284,7 +287,7 @@ describe('serialize deserialize', function () { return (window as any)._serialize(foo); }); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql({ + looseDeepEqual(deserialized, { circular: '[Circular]', }); }); @@ -298,7 +301,7 @@ describe('serialize deserialize', function () { return (window as any)._serialize(foo); }); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql({ + looseDeepEqual(deserialized, { circular1: '[Circular]', x: { circular2: '[Circular]', @@ -321,7 +324,7 @@ describe('serialize deserialize', function () { return (window as any)._serialize(foo); }); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql({ circulars: ['[Circular]', 'bar', '[Circular]'] }); + looseDeepEqual(deserialized, { circulars: ['[Circular]', 'bar', '[Circular]'] }); }); it('handles generated circular references', async () => { @@ -332,8 +335,8 @@ describe('serialize deserialize', function () { return (window as any)._serialize(obj); }); const deserialized = await deserialize(serialized); - expect(deserialized.f).to.be.a('function'); - expect(deserialized.x).to.equal('[Circular]'); + assert.equal(typeof deserialized.f, 'function'); + assert.equal(deserialized.x, '[Circular]'); }); it('handles errors', async () => { @@ -344,12 +347,12 @@ describe('serialize deserialize', function () { return (window as any)._serialize(a()); }); const deserialized = await deserialize(serialized, defaultOptions); - expect(deserialized).to.be.a('string'); - expect(deserialized).to.include('my error msg'); - expect(deserialized).to.include('2:29'); - expect(deserialized).to.include('3:29'); - expect(deserialized).to.include('4:29'); - expect(deserialized).to.include('5:38'); + assert.equal(typeof deserialized, 'string'); + assert.ok(deserialized.includes('my error msg')); + assert.match(deserialized, /2:\d+/); + assert.match(deserialized, /3:\d+/); + assert.match(deserialized, /4:\d+/); + assert.match(deserialized, /5:\d+/); }); it('handles errors in objects', async () => { @@ -360,12 +363,12 @@ describe('serialize deserialize', function () { return (window as any)._serialize({ myError: a() }); }); const deserialized = await deserialize(serialized, defaultOptions); - expect(deserialized.myError).to.be.a('string'); - expect(deserialized.myError).to.include('my error msg'); - expect(deserialized.myError).to.include('2:29'); - expect(deserialized.myError).to.include('3:29'); - expect(deserialized.myError).to.include('4:29'); - expect(deserialized.myError).to.include('5:49'); + assert.equal(typeof deserialized.myError, 'string'); + assert.ok(deserialized.myError.includes('my error msg')); + assert.match(deserialized.myError, /2:\d+/); + assert.match(deserialized.myError, /3:\d+/); + assert.match(deserialized.myError, /4:\d+/); + assert.match(deserialized.myError, /5:\d+/); }); it('handles errors in arrays', async () => { @@ -376,21 +379,21 @@ describe('serialize deserialize', function () { return (window as any)._serialize([a(), b(), c()]); }); const deserialized = await deserialize(serialized, defaultOptions); - expect(deserialized[0]).to.be.a('string'); - expect(deserialized[0]).to.include('my error msg'); - expect(deserialized[0]).to.include('2:29'); - expect(deserialized[0]).to.include('3:29'); - expect(deserialized[0]).to.include('4:29'); - expect(deserialized[0]).to.include('5:39'); - expect(deserialized[1]).to.be.a('string'); - expect(deserialized[1]).to.include('my error msg'); - expect(deserialized[1]).to.include('2:29'); - expect(deserialized[1]).to.include('3:29'); - expect(deserialized[1]).to.include('5:44'); - expect(deserialized[2]).to.be.a('string'); - expect(deserialized[2]).to.include('my error msg'); - expect(deserialized[2]).to.include('2:29'); - expect(deserialized[2]).to.include('5:49'); + assert.equal(typeof deserialized[0], 'string'); + assert.ok(deserialized[0].includes('my error msg')); + assert.match(deserialized[0], /2:\d+/); + assert.match(deserialized[0], /3:\d+/); + assert.match(deserialized[0], /4:\d+/); + assert.match(deserialized[0], /5:\d+/); + assert.equal(typeof deserialized[1], 'string'); + assert.ok(deserialized[1].includes('my error msg')); + assert.match(deserialized[1], /2:\d+/); + assert.match(deserialized[1], /3:\d+/); + assert.match(deserialized[1], /5:\d+/); + assert.equal(typeof deserialized[2], 'string'); + assert.ok(deserialized[2].includes('my error msg')); + assert.match(deserialized[2], /2:\d+/); + assert.match(deserialized[2], /5:\d+/); }); it('can map stack trace locations', async () => { @@ -404,9 +407,9 @@ describe('serialize deserialize', function () { ...defaultOptions, mapStackLocation: l => ({ ...l, filePath: `${l.filePath}__MAPPED__`, line: 1, column: 2 }), }); - expect(deserialized).to.be.a('string'); - expect(deserialized).to.include('my error msg'); - expect(deserialized).to.include(`__MAPPED__:1:2`); + assert.equal(typeof deserialized, 'string'); + assert.ok(deserialized.includes('my error msg')); + assert.ok(deserialized.includes(`__MAPPED__:1:2`)); }); it('mapped stack traces can be async', async () => { @@ -423,9 +426,9 @@ describe('serialize deserialize', function () { return { ...l, filePath: `${l.filePath}__MAPPED__`, line: 1, column: 2 }; }, }); - expect(deserialized).to.be.a('string'); - expect(deserialized).to.include('my error msg'); - expect(deserialized).to.include(`__MAPPED__:1:2`); + assert.equal(typeof deserialized, 'string'); + assert.ok(deserialized.includes('my error msg')); + assert.ok(deserialized.includes(`__MAPPED__:1:2`)); }); it('can define a cwd below current directory', async () => { @@ -437,14 +440,14 @@ describe('serialize deserialize', function () { }); const deserialized = await deserialize(serialized, { ...defaultOptions, - cwd: path.resolve(__dirname, '..'), + cwd: path.resolve(import.meta.dirname, '..'), }); - expect(deserialized).to.be.a('string'); - expect(deserialized).to.include('my error msg'); - expect(deserialized).to.include(`2:29`); - expect(deserialized).to.include(`3:29`); - expect(deserialized).to.include(`4:29`); - expect(deserialized).to.include(`5:38`); + assert.equal(typeof deserialized, 'string'); + assert.ok(deserialized.includes('my error msg')); + assert.match(deserialized, /2:\d+/); + assert.match(deserialized, /3:\d+/); + assert.match(deserialized, /4:\d+/); + assert.match(deserialized, /5:\d+/); }); it('can define a cwd above current directory', async () => { @@ -455,33 +458,33 @@ describe('serialize deserialize', function () { return (window as any)._serialize(a()); }); const deserialized = await deserialize(serialized, { - cwd: path.resolve(__dirname, '..', 'foo'), - browserRootDir: path.resolve(__dirname, '..'), + cwd: path.resolve(import.meta.dirname, '..', 'foo'), + browserRootDir: path.resolve(import.meta.dirname, '..'), }); - expect(deserialized).to.be.a('string'); - expect(deserialized).to.include('my error msg'); - expect(deserialized).to.include(`2:29`); - expect(deserialized).to.include(`3:29`); - expect(deserialized).to.include(`4:29`); - expect(deserialized).to.include(`5:38`); + assert.equal(typeof deserialized, 'string'); + assert.ok(deserialized.includes('my error msg')); + assert.match(deserialized, /2:\d+/); + assert.match(deserialized, /3:\d+/); + assert.match(deserialized, /4:\d+/); + assert.match(deserialized, /5:\d+/); }); it('handles null', async () => { const serialized = await page.evaluate(() => (window as any)._serialize(null)); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal(null); + assert.equal(deserialized, null); }); it('handles undefined', async () => { const serialized = await page.evaluate(() => (window as any)._serialize(undefined)); const deserialized = await deserialize(serialized); - expect(deserialized).to.equal(undefined); + assert.equal(deserialized, undefined); }); it('handles undefined in an object', async () => { const serialized = await page.evaluate(() => (window as any)._serialize({ x: undefined })); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql({ x: undefined }); + looseDeepEqual(deserialized, { x: undefined }); }); it('handles undefined in an array', async () => { @@ -489,7 +492,7 @@ describe('serialize deserialize', function () { (window as any)._serialize([1, undefined, '2', undefined]), ); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql([1, undefined, '2', undefined]); + looseDeepEqual(deserialized, [1, undefined, '2', undefined]); }); it('handles multiple undefined values', async () => { @@ -501,7 +504,7 @@ describe('serialize deserialize', function () { }), ); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql({ + looseDeepEqual(deserialized, { a: { a1: undefined, a2: undefined, a3: { x: undefined } }, b: undefined, c: { q: [1, undefined] }, @@ -513,7 +516,7 @@ describe('serialize deserialize', function () { (window as any)._serialize(new Promise(resolve => resolve(1))), ); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql('Promise { }'); + looseDeepEqual(deserialized, 'Promise { }'); }); it('handles errors thrown during serialization', async () => { @@ -525,6 +528,6 @@ describe('serialize deserialize', function () { }), ); const deserialized = await deserialize(serialized); - expect(deserialized).to.eql(null); + looseDeepEqual(deserialized, null); }); }); diff --git a/packages/config-loader/package.json b/packages/config-loader/package.json index 67125e67b2..9fd26f7954 100644 --- a/packages/config-loader/package.json +++ b/packages/config-loader/package.json @@ -20,8 +20,8 @@ }, "scripts": { "build": "tsc", - "test:node": "mocha test/**/*.test.js --reporter dot", - "test:watch": "mocha test/**/*.test.js --watch --watch-files .,src,test --reporter dot" + "test:node": "node --test --test-force-exit test/**/*.test.js", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.js" }, "files": [ "*.d.ts", diff --git a/packages/config-loader/test/index.test.js b/packages/config-loader/test/index.test.js index 4a6cbda32f..63d938e565 100644 --- a/packages/config-loader/test/index.test.js +++ b/packages/config-loader/test/index.test.js @@ -1,5 +1,6 @@ const path = require('path'); -const { expect } = require('chai'); +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); const { readConfig } = require('../src/index'); const configName = 'my-project.config'; @@ -12,11 +13,11 @@ async function expectThrowsOldNodeError(configPath) { await readConfig(configName, undefined, configPath); } catch (error) { thrown = true; - expect(error.message).to.include( + assert.ok(error.message.includes( 'You are trying to load a config as es module but your version of node does not support it', - ); + )); } - expect(thrown).to.equal(true); + assert.equal(thrown, true); } describe('cjs package', () => { @@ -26,7 +27,7 @@ describe('cjs package', () => { undefined, path.resolve(packageCjsPath, 'commonjs-in-.cjs'), ); - expect(result).to.eql({ foo: 'bar' }); + assert.deepEqual(result, { foo: 'bar' }); }); it('can load commonjs-in-.js', async () => { @@ -35,7 +36,7 @@ describe('cjs package', () => { undefined, path.resolve(packageCjsPath, 'commonjs-in-.js'), ); - expect(result).to.eql({ foo: 'bar' }); + assert.deepEqual(result, { foo: 'bar' }); }); it('can load module-in-.mjs', async () => { @@ -44,7 +45,7 @@ describe('cjs package', () => { undefined, path.resolve(packageCjsPath, 'module-in-.mjs'), ); - expect(result).to.eql({ foo: 'bar' }); + assert.deepEqual(result, { foo: 'bar' }); }); it('throws when loading module-in-.cjs', async () => { @@ -53,11 +54,11 @@ describe('cjs package', () => { await readConfig(configName, undefined, path.resolve(packageCjsPath, 'module-in-.cjs')); } catch (error) { thrown = true; - expect(error.message).to.include( + assert.ok(error.message.includes( 'You are using es module syntax in a config loaded as CommonJS module.', - ); + )); } - expect(thrown).to.equal(true); + assert.equal(thrown, true); }); it('throws when loading module-in-.js', async () => { @@ -66,11 +67,11 @@ describe('cjs package', () => { await readConfig(configName, undefined, path.resolve(packageCjsPath, 'module-in-.js')); } catch (error) { thrown = true; - expect(error.message).to.include( + assert.ok(error.message.includes( 'You are using es module syntax in a config loaded as CommonJS module.', - ); + )); } - expect(thrown).to.equal(true); + assert.equal(thrown, true); }); it('throws when loading commonjs-in-.mjs', async () => { @@ -79,11 +80,11 @@ describe('cjs package', () => { await readConfig(configName, undefined, path.resolve(packageCjsPath, 'commonjs-in-.mjs')); } catch (error) { thrown = true; - expect(error.message).to.include( + assert.ok(error.message.includes( 'You are using CommonJS syntax such as "require" or "module.exports" in a config loaded as es module.', - ); + )); } - expect(thrown).to.equal(true); + assert.equal(thrown, true); }); }); @@ -94,7 +95,7 @@ describe('mjs package', () => { undefined, path.resolve(packageMjsPath, 'commonjs-in-.cjs'), ); - expect(result).to.eql({ foo: 'bar' }); + assert.deepEqual(result, { foo: 'bar' }); }); it('throws when loading commonjs-in-.js', async () => { @@ -103,11 +104,11 @@ describe('mjs package', () => { await readConfig(configName, undefined, path.resolve(packageMjsPath, 'commonjs-in-.js')); } catch (error) { thrown = true; - expect(error.message).to.include( + assert.ok(error.message.includes( 'You are using CommonJS syntax such as "require" or "module.exports" in a config loaded as es module.', - ); + )); } - expect(thrown).to.equal(true); + assert.equal(thrown, true); }); it('throws when loading commonjs-in-.mjs', async () => { @@ -116,11 +117,11 @@ describe('mjs package', () => { await readConfig(configName, undefined, path.resolve(packageMjsPath, 'commonjs-in-.mjs')); } catch (error) { thrown = true; - expect(error.message).to.include( + assert.ok(error.message.includes( 'You are using CommonJS syntax such as "require" or "module.exports" in a config loaded as es module.', - ); + )); } - expect(thrown).to.equal(true); + assert.equal(thrown, true); }); it('throws when loading module-in-.cjs', async () => { @@ -129,11 +130,11 @@ describe('mjs package', () => { await readConfig(configName, undefined, path.resolve(packageCjsPath, 'module-in-.cjs')); } catch (error) { thrown = true; - expect(error.message).to.include( + assert.ok(error.message.includes( 'You are using es module syntax in a config loaded as CommonJS module.', - ); + )); } - expect(thrown).to.equal(true); + assert.equal(thrown, true); }); it('can load module-in-.js', async () => { @@ -142,7 +143,7 @@ describe('mjs package', () => { undefined, path.resolve(packageMjsPath, 'module-in-.js'), ); - expect(result).to.eql({ foo: 'bar' }); + assert.deepEqual(result, { foo: 'bar' }); }); it('can load module-in-.mjs', async () => { @@ -151,6 +152,6 @@ describe('mjs package', () => { undefined, path.resolve(packageMjsPath, 'module-in-.mjs'), ); - expect(result).to.eql({ foo: 'bar' }); + assert.deepEqual(result, { foo: 'bar' }); }); }); diff --git a/packages/dev-server-core/package.json b/packages/dev-server-core/package.json index 633e1c8378..98ea254ab2 100644 --- a/packages/dev-server-core/package.json +++ b/packages/dev-server-core/package.json @@ -39,8 +39,8 @@ "start:event-stream": "node demo/event-stream/start-server.js", "start:http2": "node demo/http2/start-server.js", "start:import-asset": "node demo/import-asset/start-server.js", - "test": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --exit --reporter dot", - "test:watch": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ ".self-signed-dev-server-ssl.cert", diff --git a/packages/dev-server-core/src/test-helpers.ts b/packages/dev-server-core/src/test-helpers.ts index 74e19db790..4bd8b8967b 100644 --- a/packages/dev-server-core/src/test-helpers.ts +++ b/packages/dev-server-core/src/test-helpers.ts @@ -1,5 +1,5 @@ import portfinder from 'portfinder'; -import { expect } from 'chai'; +import assert from 'node:assert/strict'; import { green, red, yellow } from 'nanocolors'; import { DevServer } from './server/DevServer.js'; @@ -63,7 +63,7 @@ export const timeout = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms export async function fetchText(url: string, init?: RequestInit) { const response = await fetch(url, init); - expect(response.status).to.equal(200); + assert.equal(response.status, 200); return response.text(); } diff --git a/packages/dev-server-core/test/helpers.ts b/packages/dev-server-core/test/helpers.ts index 398a0f9b2b..d99a33e866 100644 --- a/packages/dev-server-core/test/helpers.ts +++ b/packages/dev-server-core/test/helpers.ts @@ -5,12 +5,12 @@ import { fetchText, expectIncludes, virtualFilesPlugin, -} from '../src/test-helpers.js'; -import { DevServerCoreConfig } from '../src/server/DevServerCoreConfig.js'; +} from '../dist/test-helpers.js'; +import type { DevServerCoreConfig } from '../dist/server/DevServerCoreConfig.js'; export function createTestServer(config: Partial = {}) { return originalCreateTestServer({ - rootDir: path.resolve(__dirname, 'fixtures', 'basic'), + rootDir: path.resolve(import.meta.dirname, 'fixtures', 'basic'), ...config, }); } diff --git a/packages/dev-server-core/test/middleware/basePathMiddleware.test.ts b/packages/dev-server-core/test/middleware/basePathMiddleware.test.ts index 4de47b14ed..d7c2b05314 100644 --- a/packages/dev-server-core/test/middleware/basePathMiddleware.test.ts +++ b/packages/dev-server-core/test/middleware/basePathMiddleware.test.ts @@ -1,7 +1,8 @@ -import { expect } from 'chai'; +import { describe, it, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; -import { DevServer } from '../../src/server/DevServer.js'; -import { createTestServer } from '../helpers.js'; +import { DevServer } from '../../dist/server/DevServer.js'; +import { createTestServer } from '../helpers.ts'; describe('base path middleware', () => { describe('without a trailing /', () => { @@ -19,20 +20,20 @@ describe('base path middleware', () => { const response = await fetch(`${host}/foo/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); }); it('can request without base path', async () => { const response = await fetch(`${host}/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); }); }); - context('with a trailing /', () => { + describe('with a trailing /', () => { let host: string; let server: DevServer; beforeEach(async () => { @@ -47,16 +48,16 @@ describe('base path middleware', () => { const response = await fetch(`${host}/foo/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); }); it('can request without base path', async () => { const response = await fetch(`${host}/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); }); }); }); diff --git a/packages/dev-server-core/test/middleware/etagCacheMiddleware.test.ts b/packages/dev-server-core/test/middleware/etagCacheMiddleware.test.ts index 75838be21a..47307794b2 100644 --- a/packages/dev-server-core/test/middleware/etagCacheMiddleware.test.ts +++ b/packages/dev-server-core/test/middleware/etagCacheMiddleware.test.ts @@ -1,12 +1,13 @@ -import { expect } from 'chai'; +import { describe, it, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; import path from 'path'; import fs from 'fs'; import { nanoid } from 'nanoid'; -import { createTestServer, timeout } from '../helpers.js'; -import { DevServer } from '../../src/server/DevServer.js'; +import { createTestServer, timeout } from '../helpers.ts'; +import { DevServer } from '../../dist/server/DevServer.js'; -const fixtureDir = path.resolve(__dirname, '..', 'fixtures', 'basic'); +const fixtureDir = path.resolve(import.meta.dirname, '..', 'fixtures', 'basic'); const testFileAName = '/cached-file-a.js'; const testFileBName = '/cached-file-b.js'; const testFileAPath = path.join(fixtureDir, testFileAName); @@ -24,7 +25,7 @@ describe('etag cache middleware', () => { server.stop(); }); - context('', () => { + describe('', () => { beforeEach(() => { fs.writeFileSync(testFileAPath, '// this file is cached', 'utf-8'); }); @@ -37,21 +38,21 @@ describe('etag cache middleware', () => { const initialResponse = await fetch(`${host}${testFileAName}`); const etag = initialResponse.headers.get('etag')!; - expect(initialResponse.status).to.equal(200); - expect(await initialResponse.text()).to.equal('// this file is cached'); + assert.equal(initialResponse.status, 200); + assert.equal(await initialResponse.text(), '// this file is cached'); - expect(etag).to.be.a('string'); + assert.equal(typeof etag, 'string'); const cachedResponse = await fetch(`${host}${testFileAName}`, { headers: { 'If-None-Match': etag, 'Cache-Control': 'max-age=3600' }, }); - expect(cachedResponse.status).to.equal(304); - expect(await cachedResponse.text()).to.equal(''); + assert.equal(cachedResponse.status, 304); + assert.equal(await cachedResponse.text(), ''); }); }); - context('', () => { + describe('', () => { beforeEach(() => { fs.writeFileSync(testFileBPath, '// this file is cached', 'utf-8'); }); @@ -66,9 +67,9 @@ describe('etag cache middleware', () => { const initialResponse = await fetch(`${host}${testFileBName}`); const etag = initialResponse.headers.get('etag'); - expect(initialResponse.status).to.equal(200); - expect(await initialResponse.text()).to.equal('// this file is cached'); - expect(etag).to.be.a('string'); + assert.equal(initialResponse.status, 200); + assert.equal(await initialResponse.text(), '// this file is cached'); + assert.equal(typeof etag, 'string'); await timeout(10); const fileContent = `// the cache is busted${nanoid()}`; @@ -78,8 +79,8 @@ describe('etag cache middleware', () => { const headers = { headers: { 'if-none-match': etag } as Record }; const cachedResponse = await fetch(`${host}${testFileBName}`, headers); - expect(cachedResponse.status).to.equal(200); - expect(await cachedResponse.text()).to.equal(fileContent); + assert.equal(cachedResponse.status, 200); + assert.equal(await cachedResponse.text(), fileContent); }); }); }); diff --git a/packages/dev-server-core/test/middleware/historyApiFallbackMiddleware.test.ts b/packages/dev-server-core/test/middleware/historyApiFallbackMiddleware.test.ts index ba511b2f2f..9345297857 100644 --- a/packages/dev-server-core/test/middleware/historyApiFallbackMiddleware.test.ts +++ b/packages/dev-server-core/test/middleware/historyApiFallbackMiddleware.test.ts @@ -1,8 +1,9 @@ -import { expect } from 'chai'; +import { describe, it, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; import path from 'path'; -import { createTestServer } from '../helpers.js'; -import { DevServer } from '../../src/server/DevServer.js'; +import { createTestServer } from '../helpers.ts'; +import { DevServer } from '../../dist/server/DevServer.js'; describe('history api fallback middleware', () => { describe('index in root', () => { @@ -11,7 +12,7 @@ describe('history api fallback middleware', () => { beforeEach(async () => { ({ host, server } = await createTestServer({ - appIndex: path.resolve(__dirname, '..', 'fixtures', 'basic', 'index.html'), + appIndex: path.resolve(import.meta.dirname, '..', 'fixtures', 'basic', 'index.html'), })); }); @@ -23,41 +24,41 @@ describe('history api fallback middleware', () => { const response = await fetch(`${host}/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); }); it('returns the fallback index.html for non-file requests', async () => { const response = await fetch(`${host}/foo`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); }); it('returns the fallback index.html for file requests with multiple segments', async () => { const response = await fetch(`${host}/foo/bar/baz`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); }); it('does not return index.html for file requests', async () => { const response = await fetch(`${host}/src/hello-world.txt`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('Hello world!'); - expect(responseText).to.not.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('Hello world!')); + assert.ok(!responseText.includes('My app')); }); it('does return index.html for requests that have url parameters with . characters (issue 1059)', async () => { const response = await fetch(`${host}/text-files/foo/bar/?baz=open.wc`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); }); }); @@ -67,7 +68,7 @@ describe('history api fallback middleware', () => { beforeEach(async () => { ({ host, server } = await createTestServer({ - appIndex: path.resolve(__dirname, '..', 'fixtures', 'basic', 'src', 'index.html'), + appIndex: path.resolve(import.meta.dirname, '..', 'fixtures', 'basic', 'src', 'index.html'), })); }); @@ -79,40 +80,40 @@ describe('history api fallback middleware', () => { const response = await fetch(`${host}/src/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app 2'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app 2')); }); it('returns the fallback index.html for non-file requests', async () => { const response = await fetch(`${host}/src/foo`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app 2'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app 2')); }); it('returns the fallback index.html for file requests with multiple segments', async () => { const response = await fetch(`${host}/src/foo/bar/baz`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app 2'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app 2')); }); it('does not return the index.html for requests outside the index root', async () => { const response = await fetch(`${host}/foo`); const responseText = await response.text(); - expect(response.status).to.equal(404); - expect(responseText).to.not.include('My app 2'); + assert.equal(response.status, 404); + assert.ok(!responseText.includes('My app 2')); }); it('does return index.html for requests that have url parameters with . characters (issue 1059)', async () => { const response = await fetch(`${host}/src/foo/bar/?baz=open.wc`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app 2'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app 2')); }); }); }); diff --git a/packages/dev-server-core/test/middleware/pluginFileParsedMiddleware.test.ts b/packages/dev-server-core/test/middleware/pluginFileParsedMiddleware.test.ts index 844287d97a..b1934f943a 100644 --- a/packages/dev-server-core/test/middleware/pluginFileParsedMiddleware.test.ts +++ b/packages/dev-server-core/test/middleware/pluginFileParsedMiddleware.test.ts @@ -1,7 +1,8 @@ -import { expect } from 'chai'; -import { Context } from 'koa'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import type { Context } from 'koa'; -import { createTestServer } from '../helpers.js'; +import { createTestServer } from '../helpers.ts'; describe('plugin-file-parsed middleware', () => { it('is called after other plugin hooks', async () => { @@ -44,11 +45,11 @@ describe('plugin-file-parsed middleware', () => { try { const response = await fetch(`${host}/foo.js`); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.include('application/javascript'); - expect(order[order.length - 1]).to.equal('fileParsed'); - expect(context).to.exist; - expect(context!.path).to.equal('/foo.js'); + assert.equal(response.status, 200); + assert.ok(response.headers.get('content-type')!.includes('application/javascript')); + assert.equal(order[order.length - 1], 'fileParsed'); + assert.ok(context); + assert.equal(context!.path, '/foo.js'); } finally { server.stop(); } diff --git a/packages/dev-server-core/test/middleware/pluginMimeTypeMiddleware.test.ts b/packages/dev-server-core/test/middleware/pluginMimeTypeMiddleware.test.ts index 49e7c55a5c..ed9d76cdcf 100644 --- a/packages/dev-server-core/test/middleware/pluginMimeTypeMiddleware.test.ts +++ b/packages/dev-server-core/test/middleware/pluginMimeTypeMiddleware.test.ts @@ -1,6 +1,7 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; -import { createTestServer } from '../helpers.js'; +import { createTestServer } from '../helpers.ts'; describe('plugin-mime-type middleware', () => { it('can set the mime type of a file with a string', async () => { @@ -20,8 +21,8 @@ describe('plugin-mime-type middleware', () => { try { const response = await fetch(`${host}/src/hello-world.txt`); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.include('application/javascript'); + assert.equal(response.status, 200); + assert.ok(response.headers.get('content-type')!.includes('application/javascript')); } finally { server.stop(); } @@ -44,8 +45,8 @@ describe('plugin-mime-type middleware', () => { try { const response = await fetch(`${host}/src/hello-world.txt`); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.include('application/javascript'); + assert.equal(response.status, 200); + assert.ok(response.headers.get('content-type')!.includes('application/javascript')); } finally { server.stop(); } diff --git a/packages/dev-server-core/test/middleware/pluginServeMiddleware.test.ts b/packages/dev-server-core/test/middleware/pluginServeMiddleware.test.ts index baec7e2faf..27eab77097 100644 --- a/packages/dev-server-core/test/middleware/pluginServeMiddleware.test.ts +++ b/packages/dev-server-core/test/middleware/pluginServeMiddleware.test.ts @@ -1,6 +1,7 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; -import { createTestServer } from '../helpers.js'; +import { createTestServer } from '../helpers.ts'; describe('plugin-serve middleware', () => { it('can serve non-existing files', async () => { @@ -21,8 +22,8 @@ describe('plugin-serve middleware', () => { const response = await fetch(`${host}/non-existing.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('serving non-existing.js'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('serving non-existing.js')); } finally { server.stop(); } @@ -54,8 +55,8 @@ describe('plugin-serve middleware', () => { const response = await fetch(`${host}/non-existing.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('serve a'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('serve a')); } finally { server.stop(); } @@ -79,11 +80,9 @@ describe('plugin-serve middleware', () => { const response = await fetch(`${host}/non-existing.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('serving non-existing.js'); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.ok(responseText.includes('serving non-existing.js')); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); } finally { server.stop(); } @@ -105,8 +104,8 @@ describe('plugin-serve middleware', () => { try { const response = await fetch(`${host}/foo.bar`); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal('text/css; charset=utf-8'); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'text/css; charset=utf-8'); } finally { server.stop(); } @@ -130,8 +129,8 @@ describe('plugin-serve middleware', () => { const response = await fetch(`${host}/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('overwritten index.html'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('overwritten index.html')); } finally { server.stop(); } @@ -154,8 +153,8 @@ describe('plugin-serve middleware', () => { try { const response = await fetch(`${host}/index.html`); - expect(response.status).to.equal(200); - expect(response.headers.get('x-foo')).to.equal('bar'); + assert.equal(response.status, 200); + assert.equal(response.headers.get('x-foo'), 'bar'); } finally { server.stop(); } @@ -179,8 +178,8 @@ describe('plugin-serve middleware', () => { const response = await fetch(`${host}/non-existing.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('serving non-existing.js'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('serving non-existing.js')); } finally { server.stop(); } diff --git a/packages/dev-server-core/test/middleware/pluginTransformMiddleware.test.ts b/packages/dev-server-core/test/middleware/pluginTransformMiddleware.test.ts index d0fc91f2b8..8f31216990 100644 --- a/packages/dev-server-core/test/middleware/pluginTransformMiddleware.test.ts +++ b/packages/dev-server-core/test/middleware/pluginTransformMiddleware.test.ts @@ -1,8 +1,9 @@ /* eslint-disable no-restricted-syntax, no-await-in-loop */ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; -import { createTestServer } from '../helpers.js'; -import { fetchText, expectIncludes } from '../../src/test-helpers.js'; +import { createTestServer } from '../helpers.ts'; +import { fetchText, expectIncludes } from '../../dist/test-helpers.js'; describe('plugin-transform middleware', () => { it('can transform a served file', async () => { @@ -23,8 +24,8 @@ describe('plugin-transform middleware', () => { const response = await fetch(`${host}/src/hello-world.txt`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.equal('Hello world! injected text'); + assert.equal(response.status, 200); + assert.equal(responseText, 'Hello world! injected text'); } finally { server.stop(); } @@ -54,8 +55,8 @@ describe('plugin-transform middleware', () => { const response = await fetch(`${host}/non-existing.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.equal('my non existing file injected text'); + assert.equal(response.status, 200); + assert.equal(responseText, 'my non existing file injected text'); } finally { server.stop(); } @@ -87,8 +88,8 @@ describe('plugin-transform middleware', () => { const response = await fetch(`${host}/src/hello-world.txt`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.equal('Hello world! INJECT_A INJECT_B'); + assert.equal(response.status, 200); + assert.equal(responseText, 'Hello world! INJECT_A INJECT_B'); } finally { server.stop(); } @@ -112,8 +113,8 @@ describe('plugin-transform middleware', () => { const response = await fetch(`${host}/non-existing.js`); const responseText = await response.text(); - expect(response.status).to.equal(404); - expect(responseText).to.equal('Not Found'); + assert.equal(response.status, 404); + assert.equal(responseText, 'Not Found'); } finally { server.stop(); } @@ -136,8 +137,8 @@ describe('plugin-transform middleware', () => { try { const response = await fetch(`${host}/index.html`); - expect(response.status).to.equal(200); - expect(response.headers.get('x-foo')).to.equal('bar'); + assert.equal(response.status, 200); + assert.equal(response.headers.get('x-foo'), 'bar'); } finally { server.stop(); } @@ -164,7 +165,7 @@ describe('plugin-transform middleware', () => { const responseTwo = await fetch(`${host}/src/hello-world.txt`); const timestampTwo = await responseTwo.text(); - expect(timestampOne).equal(timestampTwo); + assert.equal(timestampOne, timestampTwo); } finally { server.stop(); } @@ -195,10 +196,11 @@ describe('plugin-transform middleware', () => { const textTwo = await responseTwo.text(); const headersTwo = responseTwo.headers; - expect(textOne).equal('console.log("foo")'); - expect(textTwo).equal('console.log("foo")'); - expect(headersOne.get('x-foo')).eql('bar'); - expect(Object.fromEntries(headersOne.entries())).eql( + assert.equal(textOne, 'console.log("foo")'); + assert.equal(textTwo, 'console.log("foo")'); + assert.equal(headersOne.get('x-foo'), 'bar'); + assert.deepEqual( + Object.fromEntries(headersOne.entries()), Object.fromEntries(headersTwo.entries()), ); } finally { @@ -227,7 +229,7 @@ describe('plugin-transform middleware', () => { const responseTwo = await fetch(`${host}/src/hello-world.txt`); const timestampTwo = await responseTwo.text(); - expect(timestampOne).to.not.equal(timestampTwo); + assert.notEqual(timestampOne, timestampTwo); } finally { server.stop(); } @@ -251,8 +253,8 @@ describe('plugin-transform middleware', () => { const response = await fetch(`${host}/src/hello-world.txt`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.equal('Hello world! injected text'); + assert.equal(response.status, 200); + assert.equal(responseText, 'Hello world! injected text'); } finally { server.stop(); } @@ -289,7 +291,6 @@ describe('plugin-transform middleware', () => { }); try { - // response is transformed based on user agent const responseA1 = await fetchText(`${host}/src/hello-world.txt`, { headers: { 'user-agent': 'agent-a' }, }); @@ -300,18 +301,17 @@ describe('plugin-transform middleware', () => { }); expectIncludes(responseB1, 'Hello world! injected text B 1'); - // A1 and B1 are now cached separately, we should receive them based on user agent const responseA2 = await fetchText(`${host}/src/hello-world.txt`, { headers: { 'user-agent': 'agent-a' }, }); expectIncludes(responseA2, 'Hello world! injected text A 1'); - expect(callCountA).to.equal(1); + assert.equal(callCountA, 1); const responseB2 = await fetchText(`${host}/src/hello-world.txt`, { headers: { 'user-agent': 'agent-b' }, }); expectIncludes(responseB2, 'Hello world! injected text B 1'); - expect(callCountB).to.equal(1); + assert.equal(callCountB, 1); } finally { server.stop(); } diff --git a/packages/dev-server-core/test/middleware/serveFilesMiddleware.test.ts b/packages/dev-server-core/test/middleware/serveFilesMiddleware.test.ts index 453d11d2b1..5e5c3a538f 100644 --- a/packages/dev-server-core/test/middleware/serveFilesMiddleware.test.ts +++ b/packages/dev-server-core/test/middleware/serveFilesMiddleware.test.ts @@ -1,14 +1,15 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; import path from 'path'; -import { createTestServer } from '../helpers.js'; +import { createTestServer } from '../helpers.ts'; describe('serveFilesMiddleware', () => { it('can serve files outside of the root directory', async () => { const { host, server } = await createTestServer({ plugins: [{ name: 'test' }], rootDir: path.resolve( - __dirname, + import.meta.dirname, '..', 'fixtures', 'outside-root-dir', @@ -21,8 +22,8 @@ describe('serveFilesMiddleware', () => { const response = await fetch(`${host}/__wds-outside-root__/2/node_modules/foo/index.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include("export default 'foo'"); + assert.equal(response.status, 200); + assert.ok(responseText.includes("export default 'foo'")); } finally { server.stop(); } diff --git a/packages/dev-server-core/test/plugins/mimeTypesPlugin.test.ts b/packages/dev-server-core/test/plugins/mimeTypesPlugin.test.ts index 6411081904..4143ff2c0b 100644 --- a/packages/dev-server-core/test/plugins/mimeTypesPlugin.test.ts +++ b/packages/dev-server-core/test/plugins/mimeTypesPlugin.test.ts @@ -1,6 +1,7 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; -import { createTestServer } from '../helpers.js'; +import { createTestServer } from '../helpers.ts'; describe('mimeTypesPLugin', () => { it('can configure mime types for files', async () => { @@ -22,10 +23,8 @@ describe('mimeTypesPLugin', () => { try { const response = await fetch(`${host}/foo.css`); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); } finally { server.stop(); } @@ -33,7 +32,7 @@ describe('mimeTypesPLugin', () => { it('can resolve literal paths', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, mimeTypes: { 'foo.css': 'js', }, @@ -51,14 +50,13 @@ describe('mimeTypesPLugin', () => { try { const responseA = await fetch(`${host}/foo.css`); - expect(responseA.status).to.equal(200); - expect(responseA.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(responseA.status, 200); + assert.equal(responseA.headers.get('content-type'), 'application/javascript; charset=utf-8'); const responseB = await fetch(`${host}/x/foo.css`); - expect(responseB.status).to.equal(200); - expect(responseB.headers.get('content-type')).not.to.equal( + assert.equal(responseB.status, 200); + assert.notEqual( + responseB.headers.get('content-type'), 'application/javascript; charset=utf-8', ); } finally { diff --git a/packages/dev-server-core/test/plugins/parseDynamicImport.test.ts b/packages/dev-server-core/test/plugins/parseDynamicImport.test.ts index 39b7bbb0d0..695b3b2ea1 100644 --- a/packages/dev-server-core/test/plugins/parseDynamicImport.test.ts +++ b/packages/dev-server-core/test/plugins/parseDynamicImport.test.ts @@ -1,5 +1,6 @@ -import { expect } from 'chai'; -import { parseDynamicImport } from '../../src/plugins/parseDynamicImport.js'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { parseDynamicImport } from '../../dist/plugins/parseDynamicImport.js'; describe('parseDynamicImport', () => { function testParseDynamicImport(specifier: string) { @@ -9,7 +10,7 @@ describe('parseDynamicImport', () => { it('works for " string literals', () => { const importStringA = '"./a.js"'; - expect(testParseDynamicImport(importStringA)).to.eql({ + assert.deepEqual(testParseDynamicImport(importStringA), { importString: importStringA, importSpecifier: './a.js', concatenatedString: false, @@ -19,7 +20,7 @@ describe('parseDynamicImport', () => { }); const importStringB = '"./a/b/c.js"'; - expect(testParseDynamicImport(importStringB)).to.eql({ + assert.deepEqual(testParseDynamicImport(importStringB), { importString: importStringB, importSpecifier: './a/b/c.js', concatenatedString: false, @@ -29,7 +30,7 @@ describe('parseDynamicImport', () => { }); const importStringC = '"/a/b.js"'; - expect(testParseDynamicImport(importStringC)).to.eql({ + assert.deepEqual(testParseDynamicImport(importStringC), { importString: importStringC, importSpecifier: '/a/b.js', concatenatedString: false, @@ -41,7 +42,7 @@ describe('parseDynamicImport', () => { it("works for ' string literals", () => { const importString = "'./a.js'"; - expect(testParseDynamicImport(importString)).to.eql({ + assert.deepEqual(testParseDynamicImport(importString), { importString, importSpecifier: './a.js', concatenatedString: false, @@ -53,7 +54,7 @@ describe('parseDynamicImport', () => { it('works for singlecharacter string literals', () => { const importString = "'a.js'"; - expect(testParseDynamicImport(importString)).to.eql({ + assert.deepEqual(testParseDynamicImport(importString), { importString, importSpecifier: 'a.js', concatenatedString: false, @@ -65,7 +66,7 @@ describe('parseDynamicImport', () => { it('works for ` string literals', () => { const importString = '`./a/b.js`'; - expect(testParseDynamicImport(importString)).to.eql({ + assert.deepEqual(testParseDynamicImport(importString), { importString, importSpecifier: './a/b.js', concatenatedString: true, @@ -77,7 +78,7 @@ describe('parseDynamicImport', () => { it('works for concatenated strings', () => { const importStringA = "'./a' + '.js'"; - expect(testParseDynamicImport(importStringA)).to.eql({ + assert.deepEqual(testParseDynamicImport(importStringA), { importString: importStringA, importSpecifier: "./a' + '.js", concatenatedString: true, @@ -87,7 +88,7 @@ describe('parseDynamicImport', () => { }); const importStringB = '"./a" + "/b/" + "c.js"'; - expect(testParseDynamicImport(importStringB)).to.eql({ + assert.deepEqual(testParseDynamicImport(importStringB), { importString: importStringB, importSpecifier: './a" + "/b/" + "c.js', concatenatedString: true, @@ -99,7 +100,7 @@ describe('parseDynamicImport', () => { it('works for interpolated string literals', () => { const importString = '`./a/${file}.js`'; - expect(testParseDynamicImport(importString)).to.eql({ + assert.deepEqual(testParseDynamicImport(importString), { importString, importSpecifier: './a/${file}.js', concatenatedString: true, @@ -111,7 +112,7 @@ describe('parseDynamicImport', () => { it('works for variables', () => { const importString = 'foo'; - expect(testParseDynamicImport(importString)).to.eql({ + assert.deepEqual(testParseDynamicImport(importString), { importString, importSpecifier: 'foo', concatenatedString: false, @@ -123,7 +124,7 @@ describe('parseDynamicImport', () => { it('works for single character variables', () => { const importString = 'a'; - expect(testParseDynamicImport(importString)).to.eql({ + assert.deepEqual(testParseDynamicImport(importString), { importString, importSpecifier: 'a', concatenatedString: false, @@ -135,7 +136,7 @@ describe('parseDynamicImport', () => { it('works for variables with concatenation', () => { const importString = 'foo + "x.js"'; - expect(testParseDynamicImport(importString)).to.eql({ + assert.deepEqual(testParseDynamicImport(importString), { importString, importSpecifier: 'foo + "x.js"', concatenatedString: true, @@ -147,7 +148,7 @@ describe('parseDynamicImport', () => { it('works for string literals with spaces or newlines', () => { const importStringA = ' "./a.js" '; - expect(testParseDynamicImport(importStringA)).to.eql({ + assert.deepEqual(testParseDynamicImport(importStringA), { importString: '"./a.js"', importSpecifier: './a.js', concatenatedString: false, @@ -157,7 +158,7 @@ describe('parseDynamicImport', () => { }); const importStringB = '\n "./a.js"\n '; - expect(testParseDynamicImport(importStringB)).to.eql({ + assert.deepEqual(testParseDynamicImport(importStringB), { importString: '"./a.js"', importSpecifier: './a.js', concatenatedString: false, @@ -169,7 +170,7 @@ describe('parseDynamicImport', () => { it('works for template strings with spaces or newlines', () => { const importStringA = '\n `./x/${file}.js`\n '; - expect(testParseDynamicImport(importStringA)).to.eql({ + assert.deepEqual(testParseDynamicImport(importStringA), { importString: '`./x/${file}.js`', importSpecifier: './x/${file}.js', concatenatedString: true, diff --git a/packages/dev-server-core/test/plugins/transformModuleImportsPlugin.test.ts b/packages/dev-server-core/test/plugins/transformModuleImportsPlugin.test.ts index f1ce647d2c..22a00ab378 100644 --- a/packages/dev-server-core/test/plugins/transformModuleImportsPlugin.test.ts +++ b/packages/dev-server-core/test/plugins/transformModuleImportsPlugin.test.ts @@ -1,8 +1,9 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; -import { transformImports } from '../../src/plugins/transformModuleImportsPlugin.js'; -import type { PluginSyntaxError } from '../../src/logger/PluginSyntaxError.js'; -import { createTestServer } from '../helpers.js'; +import { transformImports } from '../../dist/plugins/transformModuleImportsPlugin.js'; +import type { PluginSyntaxError } from '../../dist/logger/PluginSyntaxError.js'; +import { createTestServer } from '../helpers.ts'; const defaultFilePath = '/root/my-file.js'; const defaultResolveImport = (src: string) => `RESOLVED__${src}`; @@ -21,7 +22,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ 'import "RESOLVED__my-module";', 'import foo from "RESOLVED__my-module";', 'import { bar } from "RESOLVED__my-module";', @@ -41,7 +42,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ // "export * from 'RESOLVED__my-module';", "export { foo } from 'RESOLVED__my-module';", @@ -55,7 +56,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result).to.eql("import 'RESOLVED__my-module/bar/index.js"); + assert.deepEqual(result, "import 'RESOLVED__my-module/bar/index.js"); }); it('resolves dynamic imports', async () => { @@ -70,7 +71,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ 'import("RESOLVED__/bar.js");', // 'function lazyLoad() { return import("RESOLVED__my-module-2"); }', // 'import("RESOLVED__my-module");', @@ -89,7 +90,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ 'console.log(import.meta.url);', "import 'RESOLVED__my-module';", ]); @@ -106,7 +107,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ "import 'RESOLVED__my-module';", "// Example: import('my-module');", ]); @@ -125,7 +126,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ 'function myimport() { }', 'function my_import() { }', 'function importShim() { }', @@ -147,7 +148,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ 'import(`RESOLVED__@namespace/my-module-3/dynamic-files/${file}.js`);', 'import(`RESOLVED__my-module/dynamic-files/${file}.js`);', 'import("RESOLVED__my-module/dynamic-files" + "/" + file + ".js");', @@ -167,7 +168,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ 'import("RESOLVED__./a.js");', "import('RESOLVED__./b.js');", ]); @@ -187,7 +188,7 @@ describe('transformImports()', () => { defaultFilePath, defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ 'import( "RESOLVED__./a.js" );', 'import( "RESOLVED__./b.js" );', 'import( "./c" + ".js" );', @@ -240,7 +241,7 @@ describe('transformImports()', () => { defaultResolveImport, ); - expect(result.split('\n')).to.eql([ + assert.deepEqual(result.split('\n'), [ 'import(`./foo/${file}.js`);', 'import(`/${file}.js`);', 'import("./foo" + "/" + file + ".js");', @@ -257,13 +258,13 @@ describe('transformImports()', () => { await transformImports('\n\nconst file = "a', defaultFilePath, defaultResolveImport); } catch (error) { thrown = true; - expect((error as PluginSyntaxError).message).to.equal('Syntax error'); - expect((error as PluginSyntaxError).filePath).to.equal('/root/my-file.js'); - expect((error as PluginSyntaxError).column).to.equal(16); - expect((error as PluginSyntaxError).line).to.equal(3); + assert.equal((error as PluginSyntaxError).message, 'Syntax error'); + assert.equal((error as PluginSyntaxError).filePath, '/root/my-file.js'); + assert.equal((error as PluginSyntaxError).column, 16); + assert.equal((error as PluginSyntaxError).line, 3); } - expect(thrown).to.be.true; + assert.equal(thrown, true); }); }); @@ -284,8 +285,8 @@ describe('resolveImport', () => { const response = await fetch(`${host}/src/app.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include("import { message } from 'RESOLVED__my-module';"); + assert.equal(response.status, 200); + assert.ok(responseText.includes("import { message } from 'RESOLVED__my-module';")); } finally { server.stop(); } @@ -307,8 +308,8 @@ describe('resolveImport', () => { const response = await fetch(`${host}/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include("import { message } from 'RESOLVED__my-module';"); + assert.equal(response.status, 200); + assert.ok(responseText.includes("import { message } from 'RESOLVED__my-module';")); } finally { server.stop(); } @@ -330,8 +331,8 @@ describe('resolveImport', () => { const response = await fetch(`${host}/src/app.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include("import { message } from 'my-module';"); + assert.equal(response.status, 200); + assert.ok(responseText.includes("import { message } from 'my-module';")); } finally { server.stop(); } @@ -363,10 +364,10 @@ describe('resolveImport', () => { const responseTextA = await responseA.text(); const responseTextB = await responseB.text(); - expect(responseA.status).to.equal(200); - expect(responseB.status).to.equal(200); - expect(responseTextA).to.include("import { message } from 'RESOLVED__A__my-module';"); - expect(responseTextB).to.include("import { message } from 'RESOLVED__B__my-module';"); + assert.equal(responseA.status, 200); + assert.equal(responseB.status, 200); + assert.ok(responseTextA.includes("import { message } from 'RESOLVED__A__my-module';")); + assert.ok(responseTextB.includes("import { message } from 'RESOLVED__B__my-module';")); } finally { server.stop(); } @@ -390,9 +391,9 @@ describe('transformImport', () => { const response = await fetch(`${host}/src/app.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include("import { message } from 'my-module?transformed-1';"); - expect(responseText).to.include('./src/local-module.js?transformed-1'); + assert.equal(response.status, 200); + assert.ok(responseText.includes("import { message } from 'my-module?transformed-1';")); + assert.ok(responseText.includes('./src/local-module.js?transformed-1')); } finally { server.stop(); } @@ -420,11 +421,11 @@ describe('transformImport', () => { const response = await fetch(`${host}/src/app.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include( - "import { message } from 'my-module?transformed-1&transformed-2';", + assert.equal(response.status, 200); + assert.ok( + responseText.includes("import { message } from 'my-module?transformed-1&transformed-2';"), ); - expect(responseText).to.include('./src/local-module.js?transformed-1&transformed-2'); + assert.ok(responseText.includes('./src/local-module.js?transformed-1&transformed-2')); } finally { server.stop(); } @@ -458,11 +459,11 @@ describe('transformImport', () => { const response = await fetch(`${host}/src/app.js`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include( - "import { message } from 'my-module?transformed-1&transformed-2';", + assert.equal(response.status, 200); + assert.ok( + responseText.includes("import { message } from 'my-module?transformed-1&transformed-2';"), ); - expect(responseText).to.include('./src/local-module.js?transformed-1&transformed-2'); + assert.ok(responseText.includes('./src/local-module.js?transformed-1&transformed-2')); } finally { server.stop(); } @@ -490,7 +491,7 @@ describe('transformImport', () => { try { await fetch(`${host}/src/app.js`); - expect(receivedImports).to.eql(['RESOLVED__my-module', 'RESOLVED__./src/local-module.js']); + assert.deepEqual(receivedImports, ['RESOLVED__my-module', 'RESOLVED__./src/local-module.js']); } finally { server.stop(); } diff --git a/packages/dev-server-core/test/server/DevServer.test.ts b/packages/dev-server-core/test/server/DevServer.test.ts index 6725579117..6f68e43335 100644 --- a/packages/dev-server-core/test/server/DevServer.test.ts +++ b/packages/dev-server-core/test/server/DevServer.test.ts @@ -1,14 +1,13 @@ +import { describe, it, before, after, beforeEach, afterEach, mock } from 'node:test'; +import assert from 'node:assert/strict'; import express from 'express'; import http from 'http'; import Koa from 'koa'; import { Server } from 'net'; -import { FSWatcher } from 'chokidar'; -import { expect } from 'chai'; import portfinder from 'portfinder'; -import { Stub, stubMethod } from 'hanbi'; -import { ServerStartParams } from '../../src/plugins/Plugin.js'; -import { DevServer } from '../../src/server/DevServer.js'; -import { createTestServer } from '../helpers.js'; +import type { ServerStartParams } from '../../dist/plugins/Plugin.js'; +import { DevServer } from '../../dist/server/DevServer.js'; +import { createTestServer } from '../helpers.ts'; describe('basic', () => { let host: string; @@ -26,37 +25,37 @@ describe('basic', () => { const response = await fetch(`${host}/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); }); it('returns hidden files', async () => { const response = await fetch(`${host}/.hidden`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('this file is hidden'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('this file is hidden')); }); it('returns files in a folder', async () => { const response = await fetch(`${host}/src/hello-world.txt`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.equal('Hello world!'); + assert.equal(response.status, 200); + assert.equal(responseText, 'Hello world!'); }); it('returns a 404 for unknown files', async () => { const response = await fetch(`${host}/non-existing.js`); - expect(response.status).to.equal(404); + assert.equal(response.status, 404); }); it('sets no-cache header', async () => { const response = await fetch(`${host}/index.html`); - expect(response.status).to.equal(200); - expect(response.headers.get('cache-control')).to.equal('no-cache'); + assert.equal(response.status, 200); + assert.equal(response.headers.get('cache-control'), 'no-cache'); }); }); @@ -65,8 +64,8 @@ it('can configure the hostname', async () => { const response = await fetch(`${host}/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); server.stop(); }); @@ -93,15 +92,15 @@ describe('http2', () => { // protocol. It would be good to have a extra assertion here. Something like: // // expect(response.protocol).to.equal('http2'); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); server.stop(); }); }); it('can run in middleware mode', async () => { const { server: wdsServer } = await createTestServer({ middlewareMode: true }); - expect(wdsServer.server).to.equal(undefined); + assert.equal(wdsServer.server, undefined); const app = express(); let httpServer: http.Server; @@ -117,8 +116,8 @@ it('can run in middleware mode', async () => { const response = await fetch(`http://localhost:${port}/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); httpServer!.close(); }); @@ -136,8 +135,8 @@ it('can run multiple servers in parallel', async () => { const response = await fetch(`${result.host}/index.html`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('My app'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('My app')); result.server.stop(); } }); @@ -157,8 +156,8 @@ it('can add extra middleware', async () => { const response = await fetch(`${host}/foo`); const responseText = await response.text(); - expect(response.status).to.equal(200); - expect(responseText).to.include('response from middleware'); + assert.equal(response.status, 200); + assert.ok(responseText.includes('response from middleware')); server.stop(); }); @@ -175,11 +174,11 @@ it('calls serverStart on plugin hook on start', async () => { ], }); - expect(startArgs!).to.exist; - expect(startArgs!.app).to.be.an.instanceOf(Koa); - expect(startArgs!.server).to.be.an.instanceOf(Server); - expect(startArgs!.fileWatcher).to.be.an.instanceOf(FSWatcher); - expect(startArgs!.config).to.be.an('object'); + assert.ok(startArgs!); + assert.ok(startArgs!.app instanceof Koa); + assert.ok(startArgs!.server instanceof Server); + assert.equal(typeof startArgs!.fileWatcher.add, 'function'); + assert.equal(typeof startArgs!.config, 'object'); server.stop(); }); @@ -198,7 +197,7 @@ it('calls serverStop on plugin hook on stop', async () => { }); await server.stop(); - expect(stopCalled).to.be.true; + assert.equal(stopCalled, true); }); it('waits on server start hooks before starting', async () => { @@ -232,8 +231,8 @@ it('waits on server start hooks before starting', async () => { ], }); - expect(aFinished).to.be.true; - expect(bFinished).to.be.true; + assert.equal(aFinished, true); + assert.equal(bFinished, true); server.stop(); }); @@ -244,40 +243,39 @@ describe('disableFileWatcher', () => { * `disableFileWatch = true` actually works. * */ const setupDisableFileWatch = async (config: { disableFileWatcher: boolean }) => { - let fileWatchStub: Stub; + let fileWatchAddMock: ReturnType | undefined; const { host, server } = await createTestServer({ disableFileWatcher: config.disableFileWatcher, plugins: [ { name: 'watcher-stub', serverStart({ fileWatcher }) { - fileWatchStub = stubMethod(fileWatcher, 'add'); + fileWatchAddMock = mock.method(fileWatcher, 'add', () => fileWatcher); }, }, ], }); - // @ts-ignore - if (!fileWatchStub) { - throw new Error('Something went wrong with stubbing the file watcher'); + if (!fileWatchAddMock) { + throw new Error('Something went wrong with mocking the file watcher'); } // Ensure something is fetched to trigger all the middlewares await fetch(`${host}/index.html`); - return { fileWatchStub, host, server }; + return { fileWatchAddMock, host, server }; }; it('disables file watch when true', async () => { - const { fileWatchStub, server } = await setupDisableFileWatch({ disableFileWatcher: true }); + const { fileWatchAddMock, server } = await setupDisableFileWatch({ disableFileWatcher: true }); - expect(fileWatchStub.callCount).to.equal(0); + assert.equal(fileWatchAddMock.mock.callCount(), 0); server.stop(); }); it('leaves file watch in tact when false', async () => { - const { fileWatchStub, server } = await setupDisableFileWatch({ disableFileWatcher: false }); + const { fileWatchAddMock, server } = await setupDisableFileWatch({ disableFileWatcher: false }); - expect(fileWatchStub.callCount).to.gt(0); + assert.ok(fileWatchAddMock.mock.callCount() > 0); server.stop(); }); }); diff --git a/packages/dev-server-core/test/web-sockets/WebSocketsManager.test.ts b/packages/dev-server-core/test/web-sockets/WebSocketsManager.test.ts index 98d3d97208..32f3d350e3 100644 --- a/packages/dev-server-core/test/web-sockets/WebSocketsManager.test.ts +++ b/packages/dev-server-core/test/web-sockets/WebSocketsManager.test.ts @@ -1,8 +1,9 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; import WebSocket from 'ws'; -import { NAME_WEB_SOCKET_API } from '../../src/web-sockets/WebSocketsManager.js'; +import { NAME_WEB_SOCKET_API } from '../../dist/web-sockets/WebSocketsManager.js'; -import { createTestServer } from '../helpers.js'; +import { createTestServer } from '../helpers.ts'; function waitFor(fn: (resolve: () => void) => void, msg: string) { return new Promise((resolve, reject) => { @@ -56,7 +57,7 @@ describe('WebSocketManager', () => { const waitForMessage = waitFor(resolve => { ws.on('message', data => { - expect(data).to.equal('hello world'); + assert.equal(data, 'hello world'); resolve(); }); }, 'expected a message event'); @@ -91,13 +92,13 @@ describe('WebSocketManager', () => { const waitForMessage1 = waitFor(resolve => { ws1.on('message', data => { - expect(data).to.equal('hello world'); + assert.equal(data, 'hello world'); resolve(); }); }, 'expected message'); const waitForMessage2 = waitFor(resolve => { ws1.on('message', data => { - expect(data).to.equal('hello world'); + assert.equal(data, 'hello world'); resolve(); }); }, 'expected message'); @@ -126,8 +127,8 @@ describe('WebSocketManager', () => { const waitForMessage = waitFor(resolve => { server.webSockets!.on('message', ({ webSocket, data }) => { - expect(webSocket).to.be.an.instanceOf(WebSocket); - expect(data).to.eql({ type: 'foo' }); + assert.ok(webSocket instanceof WebSocket); + assert.deepEqual(data, { type: 'foo' }); resolve(); }); }, 'expected message event fired from manager'); @@ -156,7 +157,7 @@ describe('WebSocketManager', () => { const waitForMessage = waitFor(resolve => { ws.on('message', data => { const parsedData = JSON.parse(data as any); - expect(parsedData).to.eql({ + assert.deepEqual(parsedData, { data: { args: [], importPath: 'data:text/javascript,console.log("hello world");', @@ -191,7 +192,7 @@ describe('WebSocketManager', () => { const waitForMessage = waitFor(resolve => { ws.on('message', data => { const parsedData = JSON.parse(data as any); - expect(parsedData).to.eql({ + assert.deepEqual(parsedData, { data: { args: [], importPath: '/foo.js', diff --git a/packages/dev-server-core/test/web-sockets/webSocketsPlugin.test.ts b/packages/dev-server-core/test/web-sockets/webSocketsPlugin.test.ts index 8c59fda77b..02a91046c0 100644 --- a/packages/dev-server-core/test/web-sockets/webSocketsPlugin.test.ts +++ b/packages/dev-server-core/test/web-sockets/webSocketsPlugin.test.ts @@ -1,7 +1,8 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; -import { createTestServer } from '../helpers.js'; -import { webSocketScript } from '../../src/web-sockets/webSocketsPlugin.js'; +import { createTestServer } from '../helpers.ts'; +import { webSocketScript } from '../../dist/web-sockets/webSocketsPlugin.js'; describe('webSocketsPlugin', () => { it('injects an event stream script if a plugin has inject set and event stream is enabled', async () => { @@ -19,8 +20,8 @@ describe('webSocketsPlugin', () => { const response = await fetch(`${host}/index.html`); const body = await response.text(); - expect(response.status).to.equal(200); - expect(body).to.include(webSocketScript); + assert.equal(response.status, 200); + assert.ok(body.includes(webSocketScript)); } finally { server.stop(); } @@ -41,8 +42,8 @@ describe('webSocketsPlugin', () => { const response = await fetch(`${host}/index.html`); const body = await response.text(); - expect(response.status).to.equal(200); - expect(body).to.not.include(webSocketScript); + assert.equal(response.status, 200); + assert.ok(!body.includes(webSocketScript)); } finally { server.stop(); } @@ -54,8 +55,8 @@ describe('webSocketsPlugin', () => { const response = await fetch(`${host}/index.html`); const body = await response.text(); - expect(response.status).to.equal(200); - expect(body).to.not.include(webSocketScript); + assert.equal(response.status, 200); + assert.ok(!body.includes(webSocketScript)); } finally { server.stop(); } @@ -77,10 +78,10 @@ describe('webSocketsPlugin', () => { const bodyA = await responseA.text(); const bodyB = await responseB.text(); - expect(responseA.status).to.equal(200); - expect(responseB.status).to.equal(200); - expect(bodyA).to.not.include(webSocketScript); - expect(bodyB).to.not.include(webSocketScript); + assert.equal(responseA.status, 200); + assert.equal(responseB.status, 200); + assert.ok(!bodyA.includes(webSocketScript)); + assert.ok(!bodyB.includes(webSocketScript)); } finally { server.stop(); } diff --git a/packages/dev-server-esbuild/package.json b/packages/dev-server-esbuild/package.json index c8df9f8474..18b41b42dc 100644 --- a/packages/dev-server-esbuild/package.json +++ b/packages/dev-server-esbuild/package.json @@ -28,8 +28,8 @@ "build": "tsc", "start:demo:jsx": "es-dev-server --config demo/jsx/server.config.js", "start:demo:ts": "es-dev-server --config demo/ts/server.config.js", - "test:node": "mocha \"test/**/*.test.ts\" --require ts-node/register --reporter dot", - "test:watch": "mocha \"test/**/*.test.ts\" --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/dev-server-esbuild/test/banner-footer.test.ts b/packages/dev-server-esbuild/test/banner-footer.test.ts index d80849884f..ccd9a88ddd 100644 --- a/packages/dev-server-esbuild/test/banner-footer.test.ts +++ b/packages/dev-server-esbuild/test/banner-footer.test.ts @@ -1,15 +1,14 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { createTestServer } from '@web/dev-server-core/test-helpers'; import { expectIncludes } from '@web/dev-server-core/test-helpers'; -import { esbuildPlugin } from '../src/index.js'; - -describe('esbuildPlugin banner/footers', function () { - this.timeout(5000); +import { esbuildPlugin } from '../dist/index.js'; +describe('esbuildPlugin banner/footers', { timeout: 5000 }, () => { it('prepends custom banner', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -31,7 +30,7 @@ describe('esbuildPlugin banner/footers', function () { const indexOfBanner = text.indexOf('/* hello there */'); expectIncludes(text, '/* hello there */'); - expect(indexOfExpr).to.be.greaterThan(indexOfBanner); + assert.ok(indexOfExpr > indexOfBanner); } finally { server.stop(); } @@ -39,7 +38,7 @@ describe('esbuildPlugin banner/footers', function () { it('appends custom footer', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -61,7 +60,7 @@ describe('esbuildPlugin banner/footers', function () { const indexOfFooter = text.indexOf('/* hello there */'); expectIncludes(text, '/* hello there */'); - expect(indexOfFooter).to.be.greaterThan(indexOfExpr); + assert.ok(indexOfFooter > indexOfExpr); } finally { server.stop(); } diff --git a/packages/dev-server-esbuild/test/browser-targets.test.ts b/packages/dev-server-esbuild/test/browser-targets.test.ts index 57ab9d857a..04547c6188 100644 --- a/packages/dev-server-esbuild/test/browser-targets.test.ts +++ b/packages/dev-server-esbuild/test/browser-targets.test.ts @@ -1,74 +1,76 @@ -import { expect } from 'chai'; -import { browsers } from '@mdn/browser-compat-data'; -import { isLatestModernBrowser, getLatestStableMajor } from '../src/browser-targets.js'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import bcd from '@mdn/browser-compat-data'; +const { browsers } = bcd; +import { isLatestModernBrowser, getLatestStableMajor } from '../dist/browser-targets.js'; describe('isLatestModernBrowser', () => { it('returns true for latest Chrome', async () => { const latest = getLatestStableMajor(browsers.chrome.releases)!; - expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest) })).to.be.true; + assert.equal(isLatestModernBrowser({ name: 'Chrome', version: String(latest) }), true); }); it('returns true for latest Chrome -1', async () => { const latest = getLatestStableMajor(browsers.chrome.releases)!; - expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 1) })).to.be.true; + assert.equal(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 1) }), true); }); it('returns true for future version of Chrome', async () => { const latest = getLatestStableMajor(browsers.chrome.releases)!; - expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest + 1) })).to.be.true; + assert.equal(isLatestModernBrowser({ name: 'Chrome', version: String(latest + 1) }), true); }); it('returns true for unknown version of Chrome', async () => { - expect(isLatestModernBrowser({ name: 'Chrome', version: '9999999' })).to.be.true; + assert.equal(isLatestModernBrowser({ name: 'Chrome', version: '9999999' }), true); }); it('returns false for latest Chrome -2', async () => { const latest = getLatestStableMajor(browsers.chrome.releases)!; - expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 2) })).to.be.false; + assert.equal(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 2) }), false); }); it('returns false for latest Chrome -3', async () => { const latest = getLatestStableMajor(browsers.chrome.releases)!; - expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 3) })).to.be.false; + assert.equal(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 3) }), false); }); it('returns true for latest Chrome Headless', async () => { const latest = getLatestStableMajor(browsers.chrome.releases)!; - expect(isLatestModernBrowser({ name: 'Chrome Headless', version: String(latest) })).to.be.true; + assert.equal(isLatestModernBrowser({ name: 'Chrome Headless', version: String(latest) }), true); }); it('returns true for latest chromium', async () => { const latest = getLatestStableMajor(browsers.chrome.releases)!; - expect(isLatestModernBrowser({ name: 'Chromium', version: String(latest) })).to.be.true; + assert.equal(isLatestModernBrowser({ name: 'Chromium', version: String(latest) }), true); }); it('returns true for latest Firefox', async () => { const latest = getLatestStableMajor(browsers.firefox.releases)!; - expect(isLatestModernBrowser({ name: 'Firefox', version: String(latest) })).to.be.true; + assert.equal(isLatestModernBrowser({ name: 'Firefox', version: String(latest) }), true); }); it('returns false for latest Firefox -1', async () => { const latest = getLatestStableMajor(browsers.firefox.releases)!; - expect(isLatestModernBrowser({ name: 'Firefox', version: String(latest - 1) })).to.be.false; + assert.equal(isLatestModernBrowser({ name: 'Firefox', version: String(latest - 1) }), false); }); it('returns false for latest Firefox -2', async () => { const latest = getLatestStableMajor(browsers.firefox.releases)!; - expect(isLatestModernBrowser({ name: 'Firefox', version: String(latest - 2) })).to.be.false; + assert.equal(isLatestModernBrowser({ name: 'Firefox', version: String(latest - 2) }), false); }); it('returns true for latest Edge', async () => { const latest = getLatestStableMajor(browsers.edge.releases)!; - expect(isLatestModernBrowser({ name: 'Edge', version: String(latest) })).to.be.true; + assert.equal(isLatestModernBrowser({ name: 'Edge', version: String(latest) }), true); }); it('returns true for latest Edge -1', async () => { const latest = getLatestStableMajor(browsers.edge.releases)!; - expect(isLatestModernBrowser({ name: 'Edge', version: String(latest - 1) })).to.be.true; + assert.equal(isLatestModernBrowser({ name: 'Edge', version: String(latest - 1) }), true); }); it('returns false for latest Edge -2', async () => { const latest = getLatestStableMajor(browsers.edge.releases)!; - expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 2) })).to.be.false; + assert.equal(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 2) }), false); }); }); diff --git a/packages/dev-server-esbuild/test/json.test.ts b/packages/dev-server-esbuild/test/json.test.ts index 0d98282a95..d819b6a598 100644 --- a/packages/dev-server-esbuild/test/json.test.ts +++ b/packages/dev-server-esbuild/test/json.test.ts @@ -1,12 +1,13 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { expectIncludes, createTestServer } from '@web/dev-server-core/test-helpers'; -import { esbuildPlugin } from '../src/index.js'; +import { esbuildPlugin } from '../dist/index.js'; -describe('esbuildPlugin JSON', function () { +describe('esbuildPlugin JSON', () => { it('transforms .json files', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -24,10 +25,8 @@ describe('esbuildPlugin JSON', function () { const response = await fetch(`${host}/foo.json`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, 'var foo = "bar";'); expectIncludes(text, 'var foo_default = { foo };'); expectIncludes(text, 'export {'); diff --git a/packages/dev-server-esbuild/test/jsx.test.ts b/packages/dev-server-esbuild/test/jsx.test.ts index 8f94ba45b6..893762446f 100644 --- a/packages/dev-server-esbuild/test/jsx.test.ts +++ b/packages/dev-server-esbuild/test/jsx.test.ts @@ -1,12 +1,13 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { expectIncludes, createTestServer } from '@web/dev-server-core/test-helpers'; -import { esbuildPlugin } from '../src/index.js'; +import { esbuildPlugin } from '../dist/index.js'; -describe('esbuildPlugin JSX', function () { +describe('esbuildPlugin JSX', () => { it('transforms .jsx files', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -28,10 +29,8 @@ export function foo(bar) { const response = await fetch(`${host}/foo.jsx`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, 'React.createElement("div", {'); expectIncludes(text, 'id: "myDiv"'); expectIncludes(text, 'React.createElement(MyElement, {'); @@ -43,7 +42,7 @@ export function foo(bar) { it('can set the JSX factory', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -65,10 +64,8 @@ export function foo(bar) { const response = await fetch(`${host}/foo.jsx`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, 'h("div", {'); expectIncludes(text, 'id: "myDiv"'); expectIncludes(text, 'h(MyElement, {'); diff --git a/packages/dev-server-esbuild/test/target.test.ts b/packages/dev-server-esbuild/test/target.test.ts index d2e9ffbd36..069a6d5821 100644 --- a/packages/dev-server-esbuild/test/target.test.ts +++ b/packages/dev-server-esbuild/test/target.test.ts @@ -1,7 +1,8 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { createTestServer, expectIncludes } from '@web/dev-server-core/test-helpers'; -import { esbuildPlugin } from '../src/index.js'; +import { esbuildPlugin } from '../dist/index.js'; const modernJs = ` class MyClass { @@ -58,10 +59,10 @@ const transformedSyntax = { ], }; -describe('esbuildPlugin target', function () { +describe('esbuildPlugin target', () => { it('does not transform anything when set to esnext', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -79,10 +80,8 @@ describe('esbuildPlugin target', function () { const response = await fetch(`${host}/foo.js`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, syntax.classes); for (const e of syntax.classFields) { @@ -103,7 +102,7 @@ describe('esbuildPlugin target', function () { it('can transform to es2020', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -121,10 +120,8 @@ describe('esbuildPlugin target', function () { const response = await fetch(`${host}/foo.js`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, syntax.classes); for (const e of transformedSyntax.classFields) { @@ -145,7 +142,7 @@ describe('esbuildPlugin target', function () { it('can transform to es2019', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -163,10 +160,8 @@ describe('esbuildPlugin target', function () { const response = await fetch(`${host}/foo.js`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, syntax.classes); for (const e of transformedSyntax.classFields) { @@ -187,7 +182,7 @@ describe('esbuildPlugin target', function () { it('can transform to es2018', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -205,10 +200,8 @@ describe('esbuildPlugin target', function () { const response = await fetch(`${host}/foo.js`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, syntax.classes); for (const e of transformedSyntax.classFields) { @@ -229,7 +222,7 @@ describe('esbuildPlugin target', function () { it('can transform to es2017', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -247,10 +240,8 @@ describe('esbuildPlugin target', function () { const response = await fetch(`${host}/foo.js`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, syntax.classes); for (const e of transformedSyntax.classFields) { @@ -269,7 +260,7 @@ describe('esbuildPlugin target', function () { it('can transform to es2016', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -287,10 +278,8 @@ describe('esbuildPlugin target', function () { const response = await fetch(`${host}/foo.js`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, syntax.classes); for (const e of transformedSyntax.classFields) { @@ -309,7 +298,7 @@ describe('esbuildPlugin target', function () { it('can transform inline scripts', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -331,8 +320,8 @@ describe('esbuildPlugin target', function () { const response = await fetch(`${host}/index.html`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal('text/html; charset=utf-8'); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'text/html; charset=utf-8'); expectIncludes(text, syntax.classes); for (const e of transformedSyntax.classFields) { @@ -353,7 +342,7 @@ describe('esbuildPlugin target', function () { const importmapString = '{"imports":{"foo":"./bar.js"}}'; const jsonString = '{test:1}'; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -376,10 +365,10 @@ describe('esbuildPlugin target', function () { const response = await fetch(`${host}/index.html`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal('text/html; charset=utf-8'); - expect(text).to.include(importmapString); - expect(text).to.include(jsonString); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'text/html; charset=utf-8'); + assert.ok(text.includes(importmapString)); + assert.ok(text.includes(jsonString)); } finally { server.stop(); } diff --git a/packages/dev-server-esbuild/test/ts.test.ts b/packages/dev-server-esbuild/test/ts.test.ts index ce2ec0295e..46f5605c90 100644 --- a/packages/dev-server-esbuild/test/ts.test.ts +++ b/packages/dev-server-esbuild/test/ts.test.ts @@ -1,18 +1,17 @@ import path from 'path'; -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { createTestServer } from '@web/dev-server-core/test-helpers'; import { expectIncludes, expectNotIncludes } from '@web/dev-server-core/test-helpers'; -import { Plugin as RollupPlugin } from 'rollup'; +import type { Plugin as RollupPlugin } from 'rollup'; import { fromRollup } from '@web/dev-server-rollup'; -import { esbuildPlugin } from '../src/index.js'; - -describe('esbuildPlugin TS', function () { - this.timeout(5000); +import { esbuildPlugin } from '../dist/index.js'; +describe('esbuildPlugin TS', { timeout: 5000 }, () => { it('transforms .ts files', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -23,11 +22,11 @@ describe('esbuildPlugin TS', function () { id: number; name: string; } - + type Foo = number; - - export function foo (a: number, b: number): Foo { - return a + b + + export function foo (a: number, b: number): Foo { + return a + b }`; } }, @@ -39,10 +38,8 @@ describe('esbuildPlugin TS', function () { try { const response = await fetch(`${host}/foo.ts`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, 'export function foo(a, b) {'); expectIncludes(text, 'return a + b;'); expectIncludes(text, '}'); @@ -55,7 +52,7 @@ describe('esbuildPlugin TS', function () { it('transforms TS decorators', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -72,7 +69,11 @@ class Bar { }, esbuildPlugin({ ts: true, - tsconfig: path.join(__dirname, 'fixture', 'tsconfig-with-experimental-decorators.json'), + tsconfig: path.join( + import.meta.dirname, + 'fixture', + 'tsconfig-with-experimental-decorators.json', + ), }), ], }); @@ -81,10 +82,8 @@ class Bar { const response = await fetch(`${host}/foo.ts`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, '__decorate'); expectIncludes(text, '__publicField(this, "x", "y");'); expectIncludes( @@ -106,7 +105,7 @@ class Bar { it('resolves relative ending with .js to .ts files', async () => { const { server, host } = await createTestServer({ - rootDir: path.join(__dirname, 'fixture'), + rootDir: path.join(import.meta.dirname, 'fixture'), plugins: [ { name: 'test', @@ -119,10 +118,8 @@ class Bar { const response = await fetch(`${host}/a/b/foo.ts`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, 'import "../../x.ts";'); expectIncludes(text, 'import "../y.ts";'); expectIncludes(text, 'import "./z.ts";'); @@ -133,7 +130,7 @@ class Bar { it('does not change imports where the TS file does not exist', async () => { const { server, host } = await createTestServer({ - rootDir: path.join(__dirname, 'fixture'), + rootDir: path.join(import.meta.dirname, 'fixture'), plugins: [ { name: 'test', @@ -146,10 +143,8 @@ class Bar { const response = await fetch(`${host}/a/b/foo.ts`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, 'import "../../1.js";'); expectIncludes(text, 'import "../2.js";'); expectIncludes(text, 'import "./3.js";'); @@ -164,7 +159,7 @@ class Bar { it('does not change imports when ts transform is not enabled', async () => { const { server, host } = await createTestServer({ - rootDir: path.join(__dirname, 'fixture'), + rootDir: path.join(import.meta.dirname, 'fixture'), plugins: [ { name: 'test', @@ -177,7 +172,7 @@ class Bar { const response = await fetch(`${host}/a/b/foo.ts`); const text = await response.text(); - expect(response.status).to.equal(200); + assert.equal(response.status, 200); expectIncludes(text, "import '../../x.js';"); expectIncludes(text, "import '../y.js';"); expectIncludes(text, "import './z.js';"); @@ -188,7 +183,7 @@ class Bar { it('does not change imports in non-TS files', async () => { const { server, host } = await createTestServer({ - rootDir: path.join(__dirname, 'fixture'), + rootDir: path.join(import.meta.dirname, 'fixture'), plugins: [ { name: 'test', @@ -201,7 +196,7 @@ class Bar { const response = await fetch(`${host}/a/b/bar.js`); const text = await response.text(); - expect(response.status).to.equal(200); + assert.equal(response.status, 200); expectIncludes(text, "import '../../x.js';"); expectIncludes(text, "import '../y.js';"); expectIncludes(text, "import './z.js';"); @@ -214,7 +209,7 @@ class Bar { const plugin: RollupPlugin = { name: 'my-plugin', load(id) { - if (id === path.join(__dirname, 'app.js')) { + if (id === path.join(import.meta.dirname, 'app.js')) { return 'import "\0foo.js";'; } }, @@ -225,7 +220,7 @@ class Bar { }, }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ fromRollup(() => plugin)(), esbuildPlugin({ @@ -248,12 +243,15 @@ class Bar { it('reads tsconfig.json file', async () => { const { server, host } = await createTestServer({ - rootDir: path.join(__dirname, 'fixture'), + rootDir: path.join(import.meta.dirname, 'fixture'), plugins: [ { name: 'test', }, - esbuildPlugin({ ts: true, tsconfig: path.join(__dirname, 'fixture', 'tsconfig.json') }), + esbuildPlugin({ + ts: true, + tsconfig: path.join(import.meta.dirname, 'fixture', 'tsconfig.json'), + }), ], }); @@ -261,10 +259,8 @@ class Bar { const response = await fetch(`${host}/a/b/foo.ts`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, '__publicField(this, "prop");'); } finally { diff --git a/packages/dev-server-esbuild/test/tsx.test.ts b/packages/dev-server-esbuild/test/tsx.test.ts index 595e5e3cca..8203073b04 100644 --- a/packages/dev-server-esbuild/test/tsx.test.ts +++ b/packages/dev-server-esbuild/test/tsx.test.ts @@ -1,15 +1,14 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { createTestServer } from '@web/dev-server-core/test-helpers'; import { expectIncludes, expectNotIncludes } from '@web/dev-server-core/test-helpers'; -import { esbuildPlugin } from '../src/index.js'; - -describe('esbuildPlugin TSX', function () { - this.timeout(5000); +import { esbuildPlugin } from '../dist/index.js'; +describe('esbuildPlugin TSX', { timeout: 5000 }, () => { it('transforms .tsx files', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -23,7 +22,7 @@ interface MyInterface { type Foo = number; -export function foo (a: number, b: number): Foo { +export function foo (a: number, b: number): Foo { return
}`; } @@ -37,10 +36,8 @@ export function foo (a: number, b: number): Foo { const response = await fetch(`${host}/foo.tsx`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, 'React.createElement("div", {'); expectIncludes(text, 'id: "myDiv"'); expectIncludes(text, 'React.createElement(MyElement, {'); @@ -55,7 +52,7 @@ export function foo (a: number, b: number): Foo { it('can set the JSX factory', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -69,7 +66,7 @@ interface MyInterface { type Foo = number; -export function foo (a: number, b: number): Foo { +export function foo (a: number, b: number): Foo { return
}`; } @@ -83,10 +80,8 @@ export function foo (a: number, b: number): Foo { const response = await fetch(`${host}/foo.tsx`); const text = await response.text(); - expect(response.status).to.equal(200); - expect(response.headers.get('content-type')).to.equal( - 'application/javascript; charset=utf-8', - ); + assert.equal(response.status, 200); + assert.equal(response.headers.get('content-type'), 'application/javascript; charset=utf-8'); expectIncludes(text, 'h("div", {'); expectIncludes(text, 'id: "myDiv"'); expectIncludes(text, 'h(MyElement, {'); diff --git a/packages/dev-server-hmr/package.json b/packages/dev-server-hmr/package.json index a2445e6bc5..52779fcffa 100644 --- a/packages/dev-server-hmr/package.json +++ b/packages/dev-server-hmr/package.json @@ -28,8 +28,8 @@ "build": "tsc", "start:lit-html": "wds --config demo/lit-html/server.config.mjs", "start:vanilla": "wds --config demo/vanilla/server.config.mjs", - "test:node": "mocha \"test/**/*.test.ts\" --require ts-node/register --reporter dot", - "test:watch": "mocha \"test/**/*.test.ts\" --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/dev-server-hmr/test/HmrPlugin.test.ts b/packages/dev-server-hmr/test/HmrPlugin.test.ts index dd5e3c3763..1b3d3dce82 100644 --- a/packages/dev-server-hmr/test/HmrPlugin.test.ts +++ b/packages/dev-server-hmr/test/HmrPlugin.test.ts @@ -1,20 +1,20 @@ -import { expect } from 'chai'; -import { stubMethod, restore as restoreStubs } from 'hanbi'; +import assert from 'node:assert/strict'; +import { describe, it, afterEach, mock } from 'node:test'; import { createTestServer, fetchText, expectIncludes } from '@web/dev-server-core/test-helpers'; import { posix as pathUtil } from 'path'; -import { hmrPlugin } from '../src/index.js'; -import { NAME_HMR_CLIENT_IMPORT } from '../src/HmrPlugin.js'; -import { mockFile, mockFiles } from './utils.js'; +import { hmrPlugin } from '../dist/index.js'; +import { NAME_HMR_CLIENT_IMPORT } from '../dist/HmrPlugin.js'; +import { mockFile, mockFiles } from './utils.ts'; describe('HmrPlugin', () => { afterEach(async () => { - restoreStubs(); + mock.restoreAll(); }); it('should emit update for tracked files', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFile( '/foo.js', @@ -26,12 +26,13 @@ describe('HmrPlugin', () => { ], }); const { fileWatcher, webSockets } = server; - const stub = stubMethod(webSockets!, 'send'); + const stub = mock.method(webSockets!, 'send'); try { await fetch(`${host}/foo.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/foo.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/foo.js')); - expect(stub.firstCall!.args[0]).to.equal( + assert.equal( + stub.mock.calls[0].arguments[0], JSON.stringify({ type: 'hmr:update', url: '/foo.js', @@ -44,7 +45,7 @@ describe('HmrPlugin', () => { it('should bubble updates for changed dependencies', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFile( '/foo.js', @@ -55,13 +56,14 @@ describe('HmrPlugin', () => { ], }); const { fileWatcher, webSockets } = server; - const stub = stubMethod(webSockets!, 'send'); + const stub = mock.method(webSockets!, 'send'); try { await fetch(`${host}/foo.js`); await fetch(`${host}/bar.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/bar.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/bar.js')); - expect(stub.firstCall!.args[0]).to.equal( + assert.equal( + stub.mock.calls[0].arguments[0], JSON.stringify({ type: 'hmr:update', url: '/foo.js', @@ -74,7 +76,7 @@ describe('HmrPlugin', () => { it('should not reload if dependent handles change', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFile('/foo.js', `import '/bar.js'; import.meta.hot.accept();`), mockFile('/bar.js', `export const s = 808;`), @@ -82,14 +84,15 @@ describe('HmrPlugin', () => { ], }); const { fileWatcher, webSockets } = server; - const stub = stubMethod(webSockets!, 'send'); + const stub = mock.method(webSockets!, 'send'); try { await fetch(`${host}/foo.js`); await fetch(`${host}/bar.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/bar.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/bar.js')); - expect(stub.callCount).to.equal(1); - expect(stub.firstCall!.args[0]).to.equal( + assert.equal(stub.mock.callCount(), 1); + assert.equal( + stub.mock.calls[0].arguments[0], JSON.stringify({ type: 'hmr:update', url: '/foo.js', @@ -102,7 +105,7 @@ describe('HmrPlugin', () => { it('should reload if dependents do not handle change', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFile('/foo.js', `import '/bar.js';`), mockFile('/bar.js', `export const s = 808;`), @@ -110,14 +113,15 @@ describe('HmrPlugin', () => { ], }); const { fileWatcher, webSockets } = server; - const stub = stubMethod(webSockets!, 'send'); + const stub = mock.method(webSockets!, 'send'); try { await fetch(`${host}/foo.js`); await fetch(`${host}/bar.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/bar.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/bar.js')); - expect(stub.callCount).to.equal(1); - expect(stub.firstCall!.args[0]).to.equal( + assert.equal(stub.mock.callCount(), 1); + assert.equal( + stub.mock.calls[0].arguments[0], JSON.stringify({ type: 'hmr:reload', }), @@ -129,7 +133,7 @@ describe('HmrPlugin', () => { it('handles dependencies referenced relatively', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFile( '/root/foo.js', @@ -140,13 +144,14 @@ describe('HmrPlugin', () => { ], }); const { fileWatcher, webSockets } = server; - const stub = stubMethod(webSockets!, 'send'); + const stub = mock.method(webSockets!, 'send'); try { await fetch(`${host}/root/foo.js`); await fetch(`${host}/root/bar.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/root/bar.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/root/bar.js')); - expect(stub.firstCall!.args[0]).to.equal( + assert.equal( + stub.mock.calls[0].arguments[0], JSON.stringify({ type: 'hmr:update', url: '/root/foo.js', @@ -159,7 +164,7 @@ describe('HmrPlugin', () => { it('should bubble updates for changed dynamic import dependencies', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFile( '/foo.js', @@ -170,13 +175,14 @@ describe('HmrPlugin', () => { ], }); const { fileWatcher, webSockets } = server; - const stub = stubMethod(webSockets!, 'send'); + const stub = mock.method(webSockets!, 'send'); try { await fetch(`${host}/foo.js`); await fetch(`${host}/bar.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/bar.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/bar.js')); - expect(stub.firstCall!.args[0]).to.equal( + assert.equal( + stub.mock.calls[0].arguments[0], JSON.stringify({ type: 'hmr:update', url: '/foo.js', @@ -189,7 +195,7 @@ describe('HmrPlugin', () => { it('imports changed dependencies with a unique URL', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFiles({ '/a.js': "import '/b.js'; import '/c.js'; import.meta.hot.accept();", @@ -204,11 +210,11 @@ describe('HmrPlugin', () => { await fetchText(`${host}/a.js`); await fetchText(`${host}/b.js`); await fetchText(`${host}/c.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/b.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/b.js')); const updatedA = await fetchText(`${host}/a.js?m=1234567890123`); await fetchText(`${host}/b.js?m=1234567890123`); - expect(/import '\/b\.js\?m=\d{13}';/.test(updatedA)).to.equal(true); + assert.equal(/import '\/b\.js\?m=\d{13}';/.test(updatedA), true); expectIncludes(updatedA, "import '/c.js';"); } finally { await server.stop(); @@ -217,7 +223,7 @@ describe('HmrPlugin', () => { it('imports deeply changed dependencies with a unique URL', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFiles({ '/a.js': "import '/b.js'; import.meta.hot.accept();", @@ -232,13 +238,13 @@ describe('HmrPlugin', () => { await fetchText(`${host}/a.js`); await fetchText(`${host}/b.js`); await fetchText(`${host}/c.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/c.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/c.js')); const updatedA = await fetchText(`${host}/a.js?m=1234567890123`); const updatedB = await fetchText(`${host}/b.js?m=1234567890123`); await fetchText(`${host}/c.js?m=1234567890123`); - expect(/import '\/b\.js\?m=\d{13}';/.test(updatedA)).to.equal(true); - expect(/import '\/c\.js\?m=\d{13}';/.test(updatedB)).to.equal(true); + assert.equal(/import '\/b\.js\?m=\d{13}';/.test(updatedA), true); + assert.equal(/import '\/c\.js\?m=\d{13}';/.test(updatedB), true); } finally { await server.stop(); } @@ -246,7 +252,7 @@ describe('HmrPlugin', () => { it('multiple dependents will import deep dependency changes with a unique URL', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFiles({ '/a1.js': "import '/b.js'; import.meta.hot.accept(); // a1", @@ -264,14 +270,14 @@ describe('HmrPlugin', () => { await fetchText(`${host}/a2.js`); await fetchText(`${host}/b.js`); await fetchText(`${host}/c.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/c.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/c.js')); const updatedA1 = await fetchText(`${host}/a1.js?m=1234567890123`); const updatedA2 = await fetchText(`${host}/a2.js?m=1234567890123`); await fetchText(`${host}/b.js?m=1234567890123`); await fetchText(`${host}/c.js?m=1234567890123`); - expect(/import '\/b\.js\?m=\d{13}';/.test(updatedA1)).to.equal(true); - expect(/import '\/b\.js\?m=\d{13}';/.test(updatedA2)).to.equal(true); + assert.equal(/import '\/b\.js\?m=\d{13}';/.test(updatedA1), true); + assert.equal(/import '\/b\.js\?m=\d{13}';/.test(updatedA2), true); } finally { await server.stop(); } @@ -279,7 +285,7 @@ describe('HmrPlugin', () => { it('does not get confused by dynamic imports with non string literals', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFile( '/foo.js', @@ -290,13 +296,14 @@ describe('HmrPlugin', () => { ], }); const { fileWatcher, webSockets } = server; - const stub = stubMethod(webSockets!, 'send'); + const stub = mock.method(webSockets!, 'send'); try { await fetch(`${host}/foo.js`); await fetch(`${host}/bar.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/bar.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/bar.js')); - expect(stub.firstCall!.args[0]).to.equal( + assert.equal( + stub.mock.calls[0].arguments[0], JSON.stringify({ type: 'hmr:update', url: '/foo.js', @@ -309,7 +316,7 @@ describe('HmrPlugin', () => { it('should emit reload for tracked files', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFile( '/foo.js', @@ -321,12 +328,13 @@ describe('HmrPlugin', () => { ], }); const { fileWatcher, webSockets } = server; - const stub = stubMethod(webSockets!, 'send'); + const stub = mock.method(webSockets!, 'send'); try { await fetch(`${host}/foo.js`); - fileWatcher.emit('change', pathUtil.join(__dirname, '/foo.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/foo.js')); - expect(stub.firstCall!.args[0]).to.equal( + assert.equal( + stub.mock.calls[0].arguments[0], JSON.stringify({ type: 'hmr:reload', }), @@ -338,14 +346,14 @@ describe('HmrPlugin', () => { it('serves a hmr client', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [hmrPlugin()], }); try { const response = await fetch(`${host}${NAME_HMR_CLIENT_IMPORT}`); const body = await response.text(); - expect(body.includes('class HotModule')).to.equal(true); + assert.equal(body.includes('class HotModule'), true); } finally { await server.stop(); } @@ -353,7 +361,7 @@ describe('HmrPlugin', () => { it('transforms hmr-capable js files', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFile( '/foo.js', @@ -369,7 +377,7 @@ describe('HmrPlugin', () => { const response = await fetch(`${host}/foo.js`); const body = await response.text(); - expect(body.includes('__WDS_HMR__')).to.equal(true); + assert.equal(body.includes('__WDS_HMR__'), true); } finally { await server.stop(); } @@ -377,7 +385,7 @@ describe('HmrPlugin', () => { it('does not transform non-hmr js files', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [mockFile('/foo.js', `export const foo = 5;`), hmrPlugin()], }); @@ -385,7 +393,7 @@ describe('HmrPlugin', () => { const response = await fetch(`${host}/foo.js`); const body = await response.text(); - expect(body.includes('__WDS_HMR__')).to.equal(false); + assert.equal(body.includes('__WDS_HMR__'), false); } finally { await server.stop(); } diff --git a/packages/dev-server-hmr/test/browser.test.ts b/packages/dev-server-hmr/test/browser.test.ts index 1f3b62ca33..d9d74deb23 100644 --- a/packages/dev-server-hmr/test/browser.test.ts +++ b/packages/dev-server-hmr/test/browser.test.ts @@ -1,11 +1,11 @@ -import { expect } from 'chai'; -import { stubMethod } from 'hanbi'; +import assert from 'node:assert/strict'; +import { describe, it, before, after, mock } from 'node:test'; import { createTestServer, expectIncludes } from '@web/dev-server-core/test-helpers'; import { Browser, HTTPResponse, launch as launchPuppeteer, Page } from 'puppeteer'; import { posix as pathUtil } from 'path'; -import { hmrPlugin } from '../src/index.js'; -import { mockFiles } from './utils.js'; +import { hmrPlugin } from '../dist/index.js'; +import { mockFiles } from './utils.ts'; function trackErrors(page: Page) { const errors: any[] = []; @@ -36,8 +36,7 @@ async function mockFaviconRequests(page: Page) { }); } -describe('browser tests', function () { - this.timeout(5000); +describe('browser tests', { timeout: 5000 }, () => { let browser: Browser; before(async () => { @@ -48,9 +47,9 @@ describe('browser tests', function () { await browser.close(); }); - it('should bubble when bubbles is true', async function () { + it('should bubble when bubbles is true', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ mockFiles({ '/foo.html': '', @@ -61,20 +60,22 @@ describe('browser tests', function () { ], }); const { fileWatcher, webSockets } = server; - const stub = stubMethod(webSockets!, 'send'); + const stub = mock.method(webSockets!, 'send'); const page = await browser.newPage(); try { await page.goto(`${host}/foo.html`, { waitUntil: 'networkidle0' }); - fileWatcher.emit('change', pathUtil.join(__dirname, '/bar.js')); + fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/bar.js')); - expect(stub.callCount).to.equal(2); - expect(stub.getCall(0)!.args[0]).to.equal( + assert.equal(stub.mock.callCount(), 2); + assert.equal( + stub.mock.calls[0].arguments[0], JSON.stringify({ type: 'hmr:update', url: '/bar.js', }), ); - expect(stub.getCall(1)!.args[0]).to.equal( + assert.equal( + stub.mock.calls[1].arguments[0], JSON.stringify({ type: 'hmr:update', url: '/foo.js', @@ -86,14 +87,14 @@ describe('browser tests', function () { } }); - it('should hot replace a module', async function () { + it('should hot replace a module', async () => { const files = { '/foo.html': '', '/foo.js': 'import.meta.hot.accept(); document.body.appendChild(document.createTextNode(" a "));', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [mockFiles(files), hmrPlugin()], }); const page = await browser.newPage(); @@ -105,7 +106,7 @@ describe('browser tests', function () { expectIncludes(await page.content(), ' a '); files['/foo.js'] = files['/foo.js'].replace('" a "', '" b "'); - server.fileWatcher.emit('change', pathUtil.join(__dirname, '/foo.js')); + server.fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/foo.js')); await page.waitForResponse((r: HTTPResponse) => r.url().startsWith(`${host}/foo.js`)); expectIncludes(await page.content(), ' a b '); @@ -126,7 +127,7 @@ describe('browser tests', function () { '/bar.js': 'export default " a ";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [mockFiles(files), hmrPlugin()], }); const page = await browser.newPage(); @@ -138,7 +139,7 @@ describe('browser tests', function () { expectIncludes(await page.content(), ' a '); files['/bar.js'] = 'export default " b ";'; - server.fileWatcher.emit('change', pathUtil.join(__dirname, '/bar.js')); + server.fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/bar.js')); await page.waitForResponse((r: HTTPResponse) => r.url().startsWith(`${host}/bar.js`)); expectIncludes(await page.content(), ' a b '); @@ -164,7 +165,7 @@ describe('browser tests', function () { '/baz.js': 'export default " a ";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [mockFiles(files), hmrPlugin()], }); const page = await browser.newPage(); @@ -175,7 +176,7 @@ describe('browser tests', function () { expectIncludes(await page.content(), ' foo a bar a '); files['/baz.js'] = 'export default " b ";'; - server.fileWatcher.emit('change', pathUtil.join(__dirname, '/baz.js')); + server.fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/baz.js')); await Promise.all([ page.waitForResponse((r: HTTPResponse) => r.url().startsWith(`${host}/foo.js`)), page.waitForResponse((r: HTTPResponse) => r.url().startsWith(`${host}/bar.js`)), @@ -205,7 +206,7 @@ describe('browser tests', function () { '/baz.js': 'document.body.appendChild(document.createTextNode(" b "));', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [mockFiles(files), hmrPlugin()], }); const page = await browser.newPage(); @@ -217,7 +218,7 @@ describe('browser tests', function () { await page.evaluate('document.body.appendChild(document.createTextNode(" c "))'); expectIncludes(await page.content(), ' a b c '); - server.fileWatcher.emit('change', pathUtil.join(__dirname, '/baz.js')); + server.fileWatcher.emit('change', pathUtil.join(import.meta.dirname, '/baz.js')); await page.waitForNavigation(); expectIncludes(await page.content(), ' a b '); diff --git a/packages/dev-server-hmr/test/utils.ts b/packages/dev-server-hmr/test/utils.ts index a79c7400f1..fb7494e706 100644 --- a/packages/dev-server-hmr/test/utils.ts +++ b/packages/dev-server-hmr/test/utils.ts @@ -1,4 +1,4 @@ -import { Context } from 'koa'; +import type { Context } from 'koa'; export const mockFile = (path: string, source: string) => ({ name: `test-file:${path}`, diff --git a/packages/dev-server-import-maps/package.json b/packages/dev-server-import-maps/package.json index f76f368abd..a01b9245a5 100644 --- a/packages/dev-server-import-maps/package.json +++ b/packages/dev-server-import-maps/package.json @@ -26,9 +26,9 @@ }, "scripts": { "build": "tsc", - "test": "mocha \"test/**/*.test.ts\" --require ts-node/register", "test:browser": "node ../test-runner/dist/bin.js test-browser/test/**/*.test.{js,html} --config test-browser/web-test-runner.config.mjs", - "test:watch": "mocha \"test/**/*.test.ts\" --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/dev-server-import-maps/test/injection.test.ts b/packages/dev-server-import-maps/test/injection.test.ts index b55c2a42b1..686c6c69bf 100644 --- a/packages/dev-server-import-maps/test/injection.test.ts +++ b/packages/dev-server-import-maps/test/injection.test.ts @@ -1,11 +1,12 @@ +import { it } from 'node:test'; import { createTestServer, expectNotIncludes } from '@web/dev-server-core/test-helpers'; import { fetchText, expectIncludes, virtualFilesPlugin } from '@web/dev-server-core/test-helpers'; -import { importMapsPlugin } from '../src/importMapsPlugin.js'; +import { importMapsPlugin } from '../dist/importMapsPlugin.js'; it('can inject an import map into any page', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ virtualFilesPlugin({ '/index.html': '', @@ -28,7 +29,7 @@ it('can inject an import map into any page', async () => { it('can use an include pattern', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ virtualFilesPlugin({ '/foo/a.html': '', @@ -58,7 +59,7 @@ it('can use an include pattern', async () => { it('can use an exclude pattern', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ virtualFilesPlugin({ '/foo/a.html': '', @@ -86,7 +87,7 @@ it('can use an exclude pattern', async () => { it('treats directory paths with an implicit index.html file', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -116,7 +117,7 @@ it('treats directory paths with an implicit index.html file', async () => { it('merges with an existing import map', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ virtualFilesPlugin({ '/index.html': @@ -146,7 +147,7 @@ it('merges with an existing import map', async () => { it('merges import map scopes', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ virtualFilesPlugin({ '/index.html': @@ -176,7 +177,7 @@ it('merges import map scopes', async () => { it('the import map in the HTML file takes priority over the injected import map', async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ virtualFilesPlugin({ '/index.html': diff --git a/packages/dev-server-import-maps/test/resolving.test.ts b/packages/dev-server-import-maps/test/resolving.test.ts index bc3368a78a..db4cf58ea0 100644 --- a/packages/dev-server-import-maps/test/resolving.test.ts +++ b/packages/dev-server-import-maps/test/resolving.test.ts @@ -1,11 +1,11 @@ +import { describe, it, mock } from 'node:test'; +import assert from 'node:assert/strict'; import { fetchText, expectIncludes, virtualFilesPlugin } from '@web/dev-server-core/test-helpers'; import { createTestServer } from '@web/dev-server-core/test-helpers'; -import { expect } from 'chai'; -import { spy } from 'hanbi'; import path from 'path'; -import { importMapsPlugin } from '../src/importMapsPlugin.js'; -import { IMPORT_MAP_PARAM } from '../src/utils.js'; +import { importMapsPlugin } from '../dist/importMapsPlugin.js'; +import { IMPORT_MAP_PARAM } from '../dist/utils.js'; function createHtml(importMap: Record) { return ` @@ -33,7 +33,7 @@ describe('applies import map id', () => { '/index.html': createHtml({ foo: './mocked-foo.js' }), }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -48,7 +48,7 @@ describe('applies import map id', () => { '/index.html': createHtml({ foo: './mocked-foo.js' }), }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -63,7 +63,7 @@ describe('applies import map id', () => { '/index.html': createHtml({ foo: './mocked-foo.js' }), }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -80,7 +80,7 @@ describe('applies import map id', () => { '/app.js': 'import "foo"; import foo from "./bar.js";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -98,7 +98,7 @@ describe('applies import map id', () => { '/app.js': 'import "bar";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -124,7 +124,7 @@ describe('applies import map id', () => { '/app.js': 'import "bar";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -150,7 +150,7 @@ describe('applies import map id', () => { '/app.js': 'import "bar?foo=bar";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -169,7 +169,7 @@ describe('resolving imports', () => { '/app.js': 'import "foo";\nimport bar from "./bar.js";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -187,7 +187,7 @@ describe('resolving imports', () => { '/x/y/app.js': 'import bar from "../../bar.js";\nimport bar from "../bar.js";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -205,7 +205,7 @@ describe('resolving imports', () => { '/x/y/app.js': 'import "x";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -222,7 +222,7 @@ describe('resolving imports', () => { '/x/app.js': 'import "./y/bar.js"; \n import "./bar.js"; \n import "../bar.js";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -249,7 +249,7 @@ describe('resolving imports', () => { '/x/app.js': 'import "bar";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -274,7 +274,7 @@ describe('resolving imports', () => { '/x/app.js': 'import "bar";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -289,7 +289,7 @@ describe('resolving imports', () => { let i = 0; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -329,7 +329,7 @@ describe('resolving imports', () => { '/index.html': '', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); @@ -351,27 +351,19 @@ describe('resolving imports', () => { `, }; - const loggerSpies = { - log: spy(), - debug: spy(), - error: spy(), - warn: spy(), - group: spy(), - groupEnd: spy(), - logSyntaxError: spy(), - }; + const warnFn = mock.fn(); const logger = { - log: loggerSpies.log.handler, - debug: loggerSpies.debug.handler, - error: loggerSpies.error.handler, - warn: loggerSpies.warn.handler, - group: loggerSpies.group.handler, - groupEnd: loggerSpies.groupEnd.handler, - logSyntaxError: loggerSpies.logSyntaxError.handler, + log: mock.fn(), + debug: mock.fn(), + error: mock.fn(), + warn: warnFn, + group: mock.fn(), + groupEnd: mock.fn(), + logSyntaxError: mock.fn(), }; const { server, host } = await createTestServer( { - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }, logger, @@ -379,8 +371,8 @@ describe('resolving imports', () => { const text = await fetchText(`${host}/index.html`); expectIncludes(text, ''); - expect(loggerSpies.warn.callCount).to.equal(1); - const warning = loggerSpies.warn.getCall(0).args[0]; + assert.equal(warnFn.mock.callCount(), 1); + const warning = warnFn.mock.calls[0].arguments[0]; expectIncludes(warning, 'Failed to parse import map in "'); expectIncludes(warning, `test${path.sep}index.html": `); server.stop(); @@ -392,7 +384,7 @@ describe('resolving imports', () => { '/app.js': 'import "foo";\nimport bar from "./bar.js";', }; const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [virtualFilesPlugin(files), importMapsPlugin()], }); diff --git a/packages/dev-server-legacy/package.json b/packages/dev-server-legacy/package.json index 40f78b2c9b..c222cfea15 100644 --- a/packages/dev-server-legacy/package.json +++ b/packages/dev-server-legacy/package.json @@ -27,8 +27,8 @@ "scripts": { "build": "tsc", "start": "wds --open --config demo/server.config.mjs", - "test:node": "mocha \"test/**/*.test.ts\" --require ts-node/register --reporter dot", - "test:watch": "mocha \"test/**/*.test.ts\" --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/dev-server-legacy/test/transform-html.test.ts b/packages/dev-server-legacy/test/transform-html.test.ts index 2fdd199512..73411e0aa5 100644 --- a/packages/dev-server-legacy/test/transform-html.test.ts +++ b/packages/dev-server-legacy/test/transform-html.test.ts @@ -1,9 +1,10 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { createTestServer } from '@web/dev-server-core/test-helpers'; import { fetchText, expectIncludes } from '@web/dev-server-core/test-helpers'; -import { legacyPlugin } from '../src/legacyPlugin.js'; -import { modernUserAgents, legacyUserAgents } from './userAgents.js'; +import { legacyPlugin } from '../dist/legacyPlugin.js'; +import { modernUserAgents, legacyUserAgents } from './userAgents.ts'; const htmlBody = ` @@ -25,12 +26,10 @@ const inlineScriptHtmlBody = ` `; -describe('legacyPlugin - transform html', function () { - this.timeout(10000); - +describe('legacyPlugin - transform html', { timeout: 10000 }, () => { it(`does not do any work on a modern browser`, async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -48,13 +47,13 @@ describe('legacyPlugin - transform html', function () { headers: { 'user-agent': modernUserAgents['Chrome 78'] }, }); - expect(text.trim()).to.equal(htmlBody.trim()); + assert.equal(text.trim(), htmlBody.trim()); server.stop(); }); it(`injects polyfills into the HTML page on legacy browsers`, async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -80,7 +79,7 @@ describe('legacyPlugin - transform html', function () { it(`injects systemjs param to inline modules`, async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -104,7 +103,7 @@ describe('legacyPlugin - transform html', function () { it(`handles inline scripts`, async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -131,7 +130,7 @@ describe('legacyPlugin - transform html', function () { it(`can request inline scripts`, async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -158,7 +157,7 @@ describe('legacyPlugin - transform html', function () { it(`includes url parameters in inline script key`, async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', diff --git a/packages/dev-server-legacy/test/transform-js.test.ts b/packages/dev-server-legacy/test/transform-js.test.ts index fd035680eb..8abbd4cd6f 100644 --- a/packages/dev-server-legacy/test/transform-js.test.ts +++ b/packages/dev-server-legacy/test/transform-js.test.ts @@ -1,9 +1,10 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { createTestServer } from '@web/dev-server-core/test-helpers'; import { fetchText, expectIncludes, expectNotIncludes } from '@web/dev-server-core/test-helpers'; -import { legacyPlugin } from '../src/legacyPlugin.js'; -import { modernUserAgents, legacyUserAgents } from './userAgents.js'; +import { legacyPlugin } from '../dist/legacyPlugin.js'; +import { modernUserAgents, legacyUserAgents } from './userAgents.ts'; const modernCode = ` class Foo { @@ -16,13 +17,11 @@ async function doImport() { console.log(window?.foo?.bar);`; -describe('legacyPlugin - transform js', function () { - this.timeout(10000); - +describe('legacyPlugin - transform js', { timeout: 10000 }, () => { for (const [name, userAgent] of Object.entries(modernUserAgents)) { it(`does not do any work on ${name}`, async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -39,7 +38,7 @@ describe('legacyPlugin - transform js', function () { const text = await fetchText(`${host}/app.js`, { headers: { 'user-agent': userAgent }, }); - expect(text.trim()).to.equal(modernCode.trim()); + assert.equal(text.trim(), modernCode.trim()); server.stop(); }); } @@ -47,7 +46,7 @@ describe('legacyPlugin - transform js', function () { for (const [name, userAgent] of Object.entries(legacyUserAgents)) { it(`transforms to es5 on ${name}`, async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', @@ -78,7 +77,7 @@ describe('legacyPlugin - transform js', function () { it(`transforms to SystemJS when systemjs paramater is given ${name}`, async () => { const { server, host } = await createTestServer({ - rootDir: __dirname, + rootDir: import.meta.dirname, plugins: [ { name: 'test', diff --git a/packages/dev-server-rollup/package.json b/packages/dev-server-rollup/package.json index 21b4eb795a..d47e43cf8b 100644 --- a/packages/dev-server-rollup/package.json +++ b/packages/dev-server-rollup/package.json @@ -25,8 +25,8 @@ "node": ">=22.0.0" }, "scripts": { - "test:node": "mocha \"test/node/**/*.test.ts\" --require ts-node/register --exit --reporter dot", - "test:watch": "mocha \"test/node/**/*.test.ts\" --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/node/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/node/**/*.test.ts" }, "files": [ "*.d.ts", @@ -65,8 +65,6 @@ "@types/whatwg-url": "^11.0.0", "@web/test-runner-chrome": "^0.18.0", "@web/test-runner-core": "^0.13.0", - "chai": "^4.2.0", - "mocha": "^10.8.2", "postcss": "^8.5.14", "rollup-plugin-postcss": "^4.0.2" } diff --git a/packages/dev-server-rollup/test/node/plugins/alias.test.ts b/packages/dev-server-rollup/test/node/plugins/alias.test.ts index 70e4509ccd..c309d6fa5d 100644 --- a/packages/dev-server-rollup/test/node/plugins/alias.test.ts +++ b/packages/dev-server-rollup/test/node/plugins/alias.test.ts @@ -1,7 +1,8 @@ +import { describe, it } from 'node:test'; import rollupAlias from '@rollup/plugin-alias'; -import { createTestServer, fetchText, expectIncludes } from '../test-helpers.js'; -import { fromRollup } from '../../../src/fromRollup.js'; +import { createTestServer, fetchText, expectIncludes } from '../test-helpers.ts'; +import { fromRollup } from '../../../dist/fromRollup.js'; const alias = fromRollup(rollupAlias); diff --git a/packages/dev-server-rollup/test/node/plugins/babel.test.ts b/packages/dev-server-rollup/test/node/plugins/babel.test.ts index 0dbf5d9b60..c69169acdf 100644 --- a/packages/dev-server-rollup/test/node/plugins/babel.test.ts +++ b/packages/dev-server-rollup/test/node/plugins/babel.test.ts @@ -1,8 +1,12 @@ +import { describe, it } from 'node:test'; +import { createRequire } from 'node:module'; /// import rollupBabel from '@rollup/plugin-babel'; -import { createTestServer, fetchText, expectIncludes } from '../test-helpers.js'; -import { fromRollup } from '../../../src/index.js'; +const require = createRequire(import.meta.url); + +import { createTestServer, fetchText, expectIncludes } from '../test-helpers.ts'; +import { fromRollup } from '../../../dist/index.js'; const babel = fromRollup(rollupBabel); diff --git a/packages/dev-server-rollup/test/node/plugins/commonjs.test.ts b/packages/dev-server-rollup/test/node/plugins/commonjs.test.ts index 25f29d7595..ac945e7b3c 100644 --- a/packages/dev-server-rollup/test/node/plugins/commonjs.test.ts +++ b/packages/dev-server-rollup/test/node/plugins/commonjs.test.ts @@ -1,11 +1,12 @@ +import { describe, it } from 'node:test'; import rollupCommonjs from '@rollup/plugin-commonjs'; import { runTests } from '@web/test-runner-core/test-helpers'; import { resolve } from 'path'; import { chromeLauncher } from '@web/test-runner-chrome'; import * as path from 'path'; -import { createTestServer, fetchText, expectIncludes } from '../test-helpers.js'; -import { fromRollup } from '../../../src/index.js'; +import { createTestServer, fetchText, expectIncludes } from '../test-helpers.ts'; +import { fromRollup } from '../../../dist/index.js'; import { nodeResolvePlugin } from '@web/dev-server'; const commonjs = fromRollup(rollupCommonjs); @@ -140,7 +141,7 @@ exports.default = _default;`; }); it('can transform modules which require node-resolved modules', async () => { - const rootDir = path.resolve(__dirname, '..', 'fixtures', 'basic'); + const rootDir = path.resolve(import.meta.dirname, '..', 'fixtures', 'basic'); const { server, host } = await createTestServer({ plugins: [ { @@ -199,11 +200,11 @@ exports.default = _default;`; } }); - it('passes the in-browser tests', async function () { - this.timeout(40000); - + it('passes the in-browser tests', { timeout: 40000 }, async () => { await runTests({ - files: [resolve(__dirname, '..', 'fixtures', 'commonjs', 'commonjs-browser-test.js')], + files: [ + resolve(import.meta.dirname, '..', 'fixtures', 'commonjs', 'commonjs-browser-test.js'), + ], browsers: [chromeLauncher({ launchOptions: { devtools: false } })], plugins: [ fromRollup(rollupCommonjs)({ diff --git a/packages/dev-server-rollup/test/node/plugins/node-resolve.test.ts b/packages/dev-server-rollup/test/node/plugins/node-resolve.test.ts index 2c7912987e..a919e74018 100644 --- a/packages/dev-server-rollup/test/node/plugins/node-resolve.test.ts +++ b/packages/dev-server-rollup/test/node/plugins/node-resolve.test.ts @@ -1,10 +1,11 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import path from 'path'; import rollupNodeResolve from '@rollup/plugin-node-resolve'; import rollupCommonjs from '@rollup/plugin-commonjs'; -import { createTestServer, fetchText, expectIncludes } from '../test-helpers.js'; -import { fromRollup } from '../../../src/index.js'; -import { expect } from 'chai'; +import { createTestServer, fetchText, expectIncludes } from '../test-helpers.ts'; +import { fromRollup } from '../../../dist/index.js'; const nodeResolve = fromRollup(rollupNodeResolve, {}, { throwOnUnresolvedImport: true }); const commonjs = fromRollup(rollupCommonjs); @@ -61,7 +62,7 @@ describe('@rollup/plugin-node-resolve', () => { it('can resolve private imports in inline scripts', async () => { const { server, host } = await createTestServer({ - rootDir: path.resolve(__dirname, '..', 'fixtures', 'private-imports'), + rootDir: path.resolve(import.meta.dirname, '..', 'fixtures', 'private-imports'), plugins: [nodeResolve()], }); @@ -76,13 +77,13 @@ describe('@rollup/plugin-node-resolve', () => { it('throws when trying to access files from the package directly if they are not exposed in the export map', async () => { const { server, host } = await createTestServer({ - rootDir: path.resolve(__dirname, '..', 'fixtures', 'private-imports'), + rootDir: path.resolve(import.meta.dirname, '..', 'fixtures', 'private-imports'), plugins: [nodeResolve()], }); try { const response = await fetch(`${host}/import-private-directly.html`); - expect(response.status).to.equal(500); + assert.equal(response.status, 500); } finally { server.stop(); } @@ -105,7 +106,7 @@ describe('@rollup/plugin-node-resolve', () => { try { const response = await fetch(`${host}/test-app.js`); - expect(response.status).to.equal(500); + assert.equal(response.status, 500); } finally { server.stop(); } @@ -128,7 +129,7 @@ describe('@rollup/plugin-node-resolve', () => { try { const text = await fetchText(`${host}/test-app.js`); - expect(text).to.equal('import "/non-existing.js"; import "./src/non-existing.js";'); + assert.equal(text, 'import "/non-existing.js"; import "./src/non-existing.js";'); } finally { server.stop(); } @@ -136,7 +137,7 @@ describe('@rollup/plugin-node-resolve', () => { it('node modules resolved outside root directory with matching basename via symlink are rewritten', async () => { const { server, host } = await createTestServer({ - rootDir: path.resolve(__dirname, '..', 'fixtures', 'resolve-outside-dir'), + rootDir: path.resolve(import.meta.dirname, '..', 'fixtures', 'resolve-outside-dir'), plugins: [nodeResolve()], }); @@ -153,7 +154,7 @@ describe('@rollup/plugin-node-resolve', () => { it('node modules resolved outside root directory are rewritten', async () => { const { server, host } = await createTestServer({ - rootDir: path.resolve(__dirname, '..', 'fixtures', 'resolve-outside-dir', 'src'), + rootDir: path.resolve(import.meta.dirname, '..', 'fixtures', 'resolve-outside-dir', 'src'), plugins: [nodeResolve()], }); @@ -170,7 +171,7 @@ describe('@rollup/plugin-node-resolve', () => { it('node modules resolved outside root directory are rewritten with commonjs', async () => { const { server, host } = await createTestServer({ - rootDir: path.resolve(__dirname, '..', 'fixtures', 'resolve-outside-dir', 'src'), + rootDir: path.resolve(import.meta.dirname, '..', 'fixtures', 'resolve-outside-dir', 'src'), plugins: [commonjs(), nodeResolve()], }); diff --git a/packages/dev-server-rollup/test/node/plugins/postcss.test.ts b/packages/dev-server-rollup/test/node/plugins/postcss.test.ts index 38f1f237c4..ce2828a619 100644 --- a/packages/dev-server-rollup/test/node/plugins/postcss.test.ts +++ b/packages/dev-server-rollup/test/node/plugins/postcss.test.ts @@ -1,18 +1,19 @@ +import { describe, it } from 'node:test'; /// import rollupPostcss from 'rollup-plugin-postcss'; import { chromeLauncher } from '@web/test-runner-chrome'; import { runTests } from '@web/test-runner-core/test-helpers'; import { resolve } from 'path'; -import { createTestServer, fetchText, expectIncludes } from '../test-helpers.js'; -import { fromRollup } from '../../../src/index.js'; +import { createTestServer, fetchText, expectIncludes } from '../test-helpers.ts'; +import { fromRollup } from '../../../dist/index.js'; const postcss = fromRollup(rollupPostcss); describe('@rollup/plugin-postcss', () => { it('can run postcss on imported css files', async () => { const { server, host } = await createTestServer({ - rootDir: resolve(__dirname, '..', '..', '..', '..', '..'), + rootDir: resolve(import.meta.dirname, '..', '..', '..', '..', '..'), mimeTypes: { '**/*.css': 'js', }, @@ -57,10 +58,9 @@ html { } }); - it('passes the in-browser tests', async function () { - this.timeout(40000); + it('passes the in-browser tests', { timeout: 40000 }, async () => { await runTests({ - files: [resolve(__dirname, '..', 'fixtures', 'postcss', 'postcss-browser-test.js')], + files: [resolve(import.meta.dirname, '..', 'fixtures', 'postcss', 'postcss-browser-test.js')], browsers: [chromeLauncher()], mimeTypes: { '**/*.css': 'js', diff --git a/packages/dev-server-rollup/test/node/plugins/replace.test.ts b/packages/dev-server-rollup/test/node/plugins/replace.test.ts index 83a8b723a4..f0d8ff2986 100644 --- a/packages/dev-server-rollup/test/node/plugins/replace.test.ts +++ b/packages/dev-server-rollup/test/node/plugins/replace.test.ts @@ -1,7 +1,8 @@ +import { describe, it } from 'node:test'; import rollupReplace from '@rollup/plugin-replace'; -import { createTestServer, fetchText, expectIncludes } from '../test-helpers.js'; -import { fromRollup } from '../../../src/index.js'; +import { createTestServer, fetchText, expectIncludes } from '../test-helpers.ts'; +import { fromRollup } from '../../../dist/index.js'; const replace = fromRollup(rollupReplace as any); diff --git a/packages/dev-server-rollup/test/node/rollupBundlePlugin.test.ts b/packages/dev-server-rollup/test/node/rollupBundlePlugin.test.ts index 658812a3aa..6935c00e74 100644 --- a/packages/dev-server-rollup/test/node/rollupBundlePlugin.test.ts +++ b/packages/dev-server-rollup/test/node/rollupBundlePlugin.test.ts @@ -1,15 +1,16 @@ -import { rollupBundlePlugin } from '../../src/rollupBundlePlugin.js'; +import { describe, it } from 'node:test'; +import { rollupBundlePlugin } from '../../dist/rollupBundlePlugin.js'; import path from 'path'; -import { createTestServer, fetchText, expectIncludes } from './test-helpers.js'; +import { createTestServer, fetchText, expectIncludes } from './test-helpers.ts'; describe('rollupBundlePlugin', () => { it('can bundle a single entrypoint', async () => { const { server, host } = await createTestServer({ - rootDir: path.join(__dirname, 'fixtures', 'bundle-basic'), + rootDir: path.join(import.meta.dirname, 'fixtures', 'bundle-basic'), plugins: [ rollupBundlePlugin({ rollupConfig: { - input: path.join(__dirname, 'fixtures', 'bundle-basic', 'a.js'), + input: path.join(import.meta.dirname, 'fixtures', 'bundle-basic', 'a.js'), }, }), ], @@ -28,14 +29,14 @@ describe('rollupBundlePlugin', () => { it('can bundle multiple entrypoint', async () => { const { server, host } = await createTestServer({ - rootDir: path.join(__dirname, 'fixtures', 'bundle-multi'), + rootDir: path.join(import.meta.dirname, 'fixtures', 'bundle-multi'), plugins: [ rollupBundlePlugin({ rollupConfig: { input: [ - path.join(__dirname, 'fixtures', 'bundle-multi', 'a1.js'), - path.join(__dirname, 'fixtures', 'bundle-multi', 'a2.js'), - path.join(__dirname, 'fixtures', 'bundle-multi', 'a3.js'), + path.join(import.meta.dirname, 'fixtures', 'bundle-multi', 'a1.js'), + path.join(import.meta.dirname, 'fixtures', 'bundle-multi', 'a2.js'), + path.join(import.meta.dirname, 'fixtures', 'bundle-multi', 'a3.js'), ], output: { chunkFileNames: '[name].js', @@ -73,11 +74,11 @@ describe('rollupBundlePlugin', () => { it('can serve regular files not bundled by rollup', async () => { const { server, host } = await createTestServer({ - rootDir: path.join(__dirname, 'fixtures', 'bundle-basic'), + rootDir: path.join(import.meta.dirname, 'fixtures', 'bundle-basic'), plugins: [ rollupBundlePlugin({ rollupConfig: { - input: path.join(__dirname, 'fixtures', 'bundle-basic', 'a.js'), + input: path.join(import.meta.dirname, 'fixtures', 'bundle-basic', 'a.js'), }, }), ], @@ -94,11 +95,11 @@ describe('rollupBundlePlugin', () => { it('can serve files emitted by a rollup plugin', async () => { const { server, host } = await createTestServer({ - rootDir: path.join(__dirname, 'fixtures', 'bundle-basic'), + rootDir: path.join(import.meta.dirname, 'fixtures', 'bundle-basic'), plugins: [ rollupBundlePlugin({ rollupConfig: { - input: path.join(__dirname, 'fixtures', 'bundle-basic', 'a.js'), + input: path.join(import.meta.dirname, 'fixtures', 'bundle-basic', 'a.js'), plugins: [ { name: 'file-plugin', diff --git a/packages/dev-server-rollup/test/node/test-helpers.ts b/packages/dev-server-rollup/test/node/test-helpers.ts index 81f2e9c3f0..e4416e900e 100644 --- a/packages/dev-server-rollup/test/node/test-helpers.ts +++ b/packages/dev-server-rollup/test/node/test-helpers.ts @@ -5,12 +5,12 @@ import { fetchText, expectIncludes, } from '@web/dev-server-core/test-helpers'; -import { DevServerCoreConfig, Logger } from '@web/dev-server-core'; +import type { DevServerCoreConfig, Logger } from '@web/dev-server-core'; export function createTestServer(config: Partial = {}, mockLogger?: Logger) { return originalCreateTestServer( { - rootDir: path.resolve(__dirname, 'fixtures', 'basic'), + rootDir: path.resolve(import.meta.dirname, 'fixtures', 'basic'), ...config, }, mockLogger, diff --git a/packages/dev-server-rollup/test/node/unit.test.ts b/packages/dev-server-rollup/test/node/unit.test.ts index 073b2ab67f..57c530a24f 100644 --- a/packages/dev-server-rollup/test/node/unit.test.ts +++ b/packages/dev-server-rollup/test/node/unit.test.ts @@ -1,9 +1,10 @@ -import { Plugin as RollupPlugin, AstNode } from 'rollup'; -import { expect } from 'chai'; +import type { Plugin as RollupPlugin, AstNode } from 'rollup'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import path from 'path'; -import { createTestServer, fetchText, expectIncludes } from './test-helpers.js'; -import { fromRollup } from '../../src/index.js'; +import { createTestServer, fetchText, expectIncludes } from './test-helpers.ts'; +import { fromRollup } from '../../dist/index.js'; describe('@web/dev-server-rollup', () => { describe('resolveId', () => { @@ -68,7 +69,7 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', resolveId() { - return path.join(__dirname, 'fixtures', 'basic', 'src', 'foo.js'); + return path.join(import.meta.dirname, 'fixtures', 'basic', 'src', 'foo.js'); }, }; const { server, host } = await createTestServer({ @@ -77,14 +78,14 @@ describe('@web/dev-server-rollup', () => { try { const text = await fetchText(`${host}/app.js`); - expectIncludes(text, "import moduleA from './src/foo.js'"); + expectIncludes(text, "import moduleA from './dist/foo.js'"); } finally { server.stop(); } }); it('files resolved outside root directory are rewritten', async () => { - const resolvedId = path.resolve(__dirname, '..', '..', '..', '..', '..', 'foo.js'); + const resolvedId = path.resolve(import.meta.dirname, '..', '..', '..', '..', '..', 'foo.js'); const plugin: RollupPlugin = { name: 'my-plugin', resolveId() { @@ -106,7 +107,7 @@ describe('@web/dev-server-rollup', () => { it('files inside root directory imported by files inside or outside are resolved to be deduped in the browser', async () => { const rootDir = path.resolve( - __dirname, + import.meta.dirname, 'fixtures', 'monorepo-import-inside-from-outside', 'src', @@ -149,7 +150,7 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', load(id) { - if (id === path.join(__dirname, 'fixtures', 'basic', 'src', 'foo.js')) { + if (id === path.join(import.meta.dirname, 'fixtures', 'basic', 'src', 'foo.js')) { return 'console.log("hello world")'; } }, @@ -170,7 +171,7 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', load(id) { - if (id === path.join(__dirname, 'fixtures', 'basic', 'src', 'foo.js')) { + if (id === path.join(import.meta.dirname, 'fixtures', 'basic', 'src', 'foo.js')) { return { code: 'console.log("hello world")' }; } }, @@ -193,7 +194,7 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', transform(code, id) { - if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) { + if (id === path.join(import.meta.dirname, 'fixtures', 'basic', 'app.js')) { return `${code}\nconsole.log("transformed");`; } }, @@ -214,7 +215,7 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', transform(code, id) { - if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) { + if (id === path.join(import.meta.dirname, 'fixtures', 'basic', 'app.js')) { return { code: `${code}\nconsole.log("transformed");` }; } }, @@ -237,7 +238,7 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', transform(code, id) { - if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) { + if (id === path.join(import.meta.dirname, 'fixtures', 'basic', 'app.js')) { parsed = this.parse(code, {}); return undefined; } @@ -249,7 +250,7 @@ describe('@web/dev-server-rollup', () => { try { await fetchText(`${host}/app.js`); - expect(parsed).to.exist; + assert.ok(parsed); } finally { server.stop(); } @@ -259,9 +260,9 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', transform(code, id) { - if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) { + if (id === path.join(import.meta.dirname, 'fixtures', 'basic', 'app.js')) { return `import "${path - .join(__dirname, 'fixtures', 'basic', 'foo.js') + .join(import.meta.dirname, 'fixtures', 'basic', 'foo.js') .split('\\') .join('/')}";\n${code}`; } @@ -283,7 +284,7 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', load(id) { - if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) { + if (id === path.join(import.meta.dirname, 'fixtures', 'basic', 'app.js')) { return 'import "\0foo.js";'; } }, @@ -335,7 +336,7 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', transform(code, id) { - if (id === path.join(__dirname, 'fixtures', 'basic', 'foo.html')) { + if (id === path.join(import.meta.dirname, 'fixtures', 'basic', 'foo.html')) { return { code: code.replace('foo', 'transformed') }; } }, @@ -347,7 +348,8 @@ describe('@web/dev-server-rollup', () => { try { const text = await fetchText(`${host}/foo.html`); - expect(text).to.equal( + assert.equal( + text, `\n \n \n\n`, ); } finally { @@ -359,7 +361,7 @@ describe('@web/dev-server-rollup', () => { const plugin: RollupPlugin = { name: 'my-plugin', transform(code, id) { - if (id === path.join(__dirname, 'fixtures', 'basic', 'multiple-inline.html')) { + if (id === path.join(import.meta.dirname, 'fixtures', 'basic', 'multiple-inline.html')) { return { code: code.replace('bar', 'transformed') }; } }, @@ -371,7 +373,8 @@ describe('@web/dev-server-rollup', () => { try { const text = await fetchText(`${host}/multiple-inline.html`); - expect(text).to.equal( + assert.equal( + text, `\n \n \n \n\n`, ); } finally { diff --git a/packages/dev-server/package.json b/packages/dev-server/package.json index 1659a94710..a7f0535226 100644 --- a/packages/dev-server/package.json +++ b/packages/dev-server/package.json @@ -37,8 +37,8 @@ "start:plugin-serve": "node dist/bin.js --config demo/plugin-serve/config.mjs --open", "start:static": "node dist/bin.js --config demo/static/config.mjs --open demo/static/", "start:syntax": "node dist/bin.js --config demo/syntax/config.mjs --open demo/syntax/", - "test:node": "mocha \"test/**/*.test.mjs\" --reporter dot", - "test:watch": "mocha \"test/**/*.test.mjs\" --watch --watch-files src,test --reporter dot" + "test:node": "node --test --test-force-exit test/**/*.test.mjs", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.mjs" }, "files": [ "*.d.ts", diff --git a/packages/dev-server/test/integration.test.mjs b/packages/dev-server/test/integration.test.mjs index 17a2ba372a..d6e2a939e4 100644 --- a/packages/dev-server/test/integration.test.mjs +++ b/packages/dev-server/test/integration.test.mjs @@ -1,11 +1,9 @@ +import { describe, it, before, after, beforeEach, afterEach } from 'node:test'; import puppeteer from 'puppeteer'; import path from 'path'; -import { fileURLToPath } from 'url'; import { startDevServer } from '../index.mjs'; -const dirname = path.dirname(fileURLToPath(import.meta.url)); - const testCases = [ { name: 'base-path', @@ -53,15 +51,14 @@ describe('integration tests', () => { }); for (const testCase of testCases) { - describe(`testcase ${testCase.name}`, function test() { - this.timeout(30000); + describe(`testcase ${testCase.name}`, { timeout: 30000 }, () => { let server; beforeEach(async () => { server = await startDevServer({ autoExitProcess: false, logStartMessage: false, - argv: ['--config', path.join(dirname, `../demo/${testCase.name}/config.mjs`)], + argv: ['--config', path.join(import.meta.dirname, `../demo/${testCase.name}/config.mjs`)], }); }); @@ -69,7 +66,7 @@ describe('integration tests', () => { await server.stop(); }); - it('passes the in-browser tests', async function it() { + it('passes the in-browser tests', async () => { const openPath = `/demo/${testCase.name}/`; const browserPath = `http://${server.config.hostname}:${server.config.port}${openPath}`; const page = await browser.newPage(); @@ -79,7 +76,6 @@ describe('integration tests', () => { const browserTests = await page.evaluate(() => window.__tests); - // the demos run "tests", which we check here for (const test of testCase.tests) { if (!browserTests[test]) { throw new Error(`Expected test ${test} to have passed in the browser.`); diff --git a/packages/parse5-utils/package.json b/packages/parse5-utils/package.json index 7456606506..75f932268a 100644 --- a/packages/parse5-utils/package.json +++ b/packages/parse5-utils/package.json @@ -26,8 +26,8 @@ }, "scripts": { "build": "tsc", - "test:node": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --reporter dot", - "test:watch": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --watch" + "test:node": "node --test --test-force-exit test/**/*.test.js", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.js" }, "files": [ "*.d.ts", diff --git a/packages/parse5-utils/test/index.test.js b/packages/parse5-utils/test/index.test.js index 28db8eb7a7..8e429dd4b0 100644 --- a/packages/parse5-utils/test/index.test.js +++ b/packages/parse5-utils/test/index.test.js @@ -1,4 +1,5 @@ -const { expect } = require('chai'); +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); const { parse, serialize } = require('parse5'); const { getAttribute, getTextContent, findElement } = require('../src/index'); const utils = require('../src/index'); @@ -9,7 +10,8 @@ describe('parse5-utils', () => { const doc = parse(''); const el = utils.createElement('my-element'); utils.appendChild(doc, el); - expect(serialize(doc)).to.equal( + assert.equal( + serialize(doc), '', ); }); @@ -18,7 +20,8 @@ describe('parse5-utils', () => { const doc = parse(''); const el = utils.createElement('my-element', { foo: 'bar', x: '' }); utils.appendChild(doc, el); - expect(serialize(doc)).to.equal( + assert.equal( + serialize(doc), '', ); }); @@ -29,14 +32,15 @@ describe('parse5-utils', () => { const doc = parse(''); const el = utils.createScript(); utils.appendChild(doc, el); - expect(serialize(doc)).to.equal(''); + assert.equal(serialize(doc), ''); }); it('create a script with attributes', () => { const doc = parse(''); const el = utils.createScript({ type: 'module' }); utils.appendChild(doc, el); - expect(serialize(doc)).to.equal( + assert.equal( + serialize(doc), '', ); }); @@ -45,7 +49,8 @@ describe('parse5-utils', () => { const doc = parse(''); const el = utils.createScript({ type: 'module' }, 'console.log("x");'); utils.appendChild(doc, el); - expect(serialize(doc)).to.equal( + assert.equal( + serialize(doc), '', ); }); @@ -53,47 +58,49 @@ describe('parse5-utils', () => { describe('isHtmlFragment()', () => { it('returns whether a HTML string is a fragment', () => { - expect(utils.isHtmlFragment('')).to.equal(true); - expect(utils.isHtmlFragment('')).to.equal(true); - expect(utils.isHtmlFragment('foo')).to.equal(true); - expect(utils.isHtmlFragment('
')).to.equal(true); - expect(utils.isHtmlFragment('')).to.equal( + assert.equal(utils.isHtmlFragment(''), true); + assert.equal(utils.isHtmlFragment(''), true); + assert.equal(utils.isHtmlFragment('foo'), true); + assert.equal(utils.isHtmlFragment('
'), true); + assert.equal( + utils.isHtmlFragment(''), false, ); - expect( + assert.equal( utils.isHtmlFragment(``), - ).to.equal(false); - expect(utils.isHtmlFragment('')).to.equal(false); - expect(utils.isHtmlFragment(' ')).to.equal(false); - expect(utils.isHtmlFragment(' ')).to.equal(false); - expect(utils.isHtmlFragment(' ')).to.equal(false); - expect(utils.isHtmlFragment(' ')).to.equal(false); + false, + ); + assert.equal(utils.isHtmlFragment(''), false); + assert.equal(utils.isHtmlFragment(' '), false); + assert.equal(utils.isHtmlFragment(' '), false); + assert.equal(utils.isHtmlFragment(' '), false); + assert.equal(utils.isHtmlFragment(' '), false); }); }); describe('getAttributes()', () => { it('returns the attributes of an element', () => { const el = utils.createElement('my-element', { foo: 'bar', x: '' }); - expect(utils.getAttributes(el)).to.eql({ foo: 'bar', x: '' }); + assert.deepEqual(utils.getAttributes(el), { foo: 'bar', x: '' }); }); it('returns an empty object if there are no attributes', () => { const el = utils.createElement('my-element'); - expect(utils.getAttributes(el)).to.eql({}); + assert.deepEqual(utils.getAttributes(el), {}); }); }); describe('getAttribute()', () => { it('returns a single attribute', () => { const el = utils.createElement('my-element', { foo: 'bar', x: '' }); - expect(utils.getAttribute(el, 'foo')).to.eql('bar'); + assert.deepEqual(utils.getAttribute(el, 'foo'), 'bar'); }); it('returns undefined if the attribute was not found', () => { const el = utils.createElement('my-element', { foo: 'bar', x: '' }); - expect(utils.getAttribute(el, 'y')).to.eql(undefined); + assert.deepEqual(utils.getAttribute(el, 'y'), undefined); }); }); @@ -103,7 +110,8 @@ describe('parse5-utils', () => { const el = utils.createElement('my-element'); utils.appendChild(doc, el); utils.setAttribute(el, 'foo', 'bar'); - expect(serialize(doc)).to.eql( + assert.deepEqual( + serialize(doc), '', ); }); @@ -113,7 +121,8 @@ describe('parse5-utils', () => { const el = utils.createElement('my-element', { foo: 'bar' }); utils.appendChild(doc, el); utils.setAttribute(el, 'foo', 'not-bar'); - expect(serialize(doc)).to.eql( + assert.deepEqual( + serialize(doc), '', ); }); @@ -125,7 +134,8 @@ describe('parse5-utils', () => { const el = utils.createElement('my-element'); utils.appendChild(doc, el); utils.setAttributes(el, { foo: 'bar', lorem: 'ipsum', x: undefined }); - expect(serialize(doc)).to.eql( + assert.deepEqual( + serialize(doc), '', ); }); @@ -137,7 +147,8 @@ describe('parse5-utils', () => { const el = utils.createElement('my-element', { foo: 'bar', x: 'y' }); utils.appendChild(doc, el); utils.removeAttribute(el, 'x'); - expect(serialize(doc)).to.eql( + assert.deepEqual( + serialize(doc), '', ); }); @@ -148,7 +159,7 @@ describe('parse5-utils', () => { const doc = parse('
Hello world
'); const myDiv = utils.findElement(doc, e => getAttribute(e, 'id') === 'myDiv'); if (!myDiv) throw new Error(); - expect(getTextContent(myDiv)).to.equal('Hello world'); + assert.equal(getTextContent(myDiv), 'Hello world'); }); it('returns multiple nodes text', () => { @@ -157,7 +168,7 @@ describe('parse5-utils', () => { ); const myDiv = utils.findElement(doc, e => getAttribute(e, 'id') === 'myDiv'); if (!myDiv) throw new Error(); - expect(getTextContent(myDiv)).to.equal('Top levelBeforeABAfter'); + assert.equal(getTextContent(myDiv), 'Top levelBeforeABAfter'); }); }); @@ -167,7 +178,8 @@ describe('parse5-utils', () => { const el = utils.createElement('script'); utils.setTextContent(el, 'foo bar'); utils.appendChild(doc, el); - expect(serialize(doc)).to.equal( + assert.equal( + serialize(doc), '', ); }); @@ -179,7 +191,7 @@ describe('parse5-utils', () => { const div = findElement(doc, e => utils.getAttribute(e, 'id') === 'myDiv'); if (!div) throw new Error('element not found'); utils.remove(div); - expect(serialize(doc)).to.equal(''); + assert.equal(serialize(doc), ''); }); }); @@ -198,7 +210,7 @@ describe('parse5-utils', () => { if (!found) { throw new Error('No element found.'); } - expect(utils.getAttribute(found, 'foo')).to.equal('2'); + assert.equal(utils.getAttribute(found, 'foo'), '2'); }); it('returns the first match', () => { @@ -215,8 +227,8 @@ describe('parse5-utils', () => { if (!found) { throw new Error('No element found.'); } - expect(utils.getAttribute(found, 'foo')).to.equal('bar'); - expect(utils.getAttribute(found, 'index')).to.equal('1'); + assert.equal(utils.getAttribute(found, 'foo'), 'bar'); + assert.equal(utils.getAttribute(found, 'index'), '1'); }); it('returns nested elements', () => { @@ -239,7 +251,7 @@ describe('parse5-utils', () => { if (!found) { throw new Error('No element found.'); } - expect(found).to.exist; + assert.ok(found); }); }); @@ -255,8 +267,8 @@ describe('parse5-utils', () => { `); const found = utils.findElements(doc, el => utils.getAttribute(el, 'foo') === '2'); - expect(found.length).to.equal(1); - expect(utils.getAttribute(found[0], 'foo')).to.equal('2'); + assert.equal(found.length, 1); + assert.equal(utils.getAttribute(found[0], 'foo'), '2'); }); it('returns multiple matched elements', () => { @@ -270,9 +282,9 @@ describe('parse5-utils', () => { `); const found = utils.findElements(doc, el => utils.getAttribute(el, 'foo') === 'bar'); - expect(found.length).to.equal(3); + assert.equal(found.length, 3); const indices = found.map(f => utils.getAttribute(f, 'index')); - expect(indices).to.eql(['1', '2', '3']); + assert.deepEqual(indices, ['1', '2', '3']); }); it('returns an empty array when there are no matches', () => { @@ -286,7 +298,7 @@ describe('parse5-utils', () => { `); const found = utils.findElements(doc, el => utils.hasAttribute(el, 'non-existing')); - expect(found.length).to.equal(0); + assert.equal(found.length, 0); }); it('returns child elements within template elements', () => { @@ -301,7 +313,7 @@ describe('parse5-utils', () => { `); const found = utils.findElements(doc, el => utils.hasAttribute(el, 'src')); - expect(found.length).to.equal(1); + assert.equal(found.length, 1); }); }); @@ -310,7 +322,7 @@ describe('parse5-utils', () => { const document = ''; const result = utils.prependToDocument(document, '
Hello world
'); if (!result) throw new Error(); - expect(result).to.equal('
Hello world
'); + assert.equal(result, '
Hello world
'); }); it('injects before other elements', () => { @@ -318,7 +330,8 @@ describe('parse5-utils', () => { '
A
B
C
'; const result = utils.prependToDocument(document, '
Hello world
'); if (!result) throw new Error(); - expect(result).to.equal( + assert.equal( + result, '
Hello world
A
B
C
', ); }); @@ -327,13 +340,13 @@ describe('parse5-utils', () => { const document = '
A
'; const result = utils.prependToDocument(document, '
Hello world
'); if (!result) throw new Error(); - expect(result).to.equal('
Hello world
A
'); + assert.equal(result, '
Hello world
A
'); }); it('uses AST manipulation if there is no head or body', () => { const document = ''; const result = utils.prependToDocument(document, '
A
B
'); - expect(result).to.equal('
A
B
'); + assert.equal(result, '
A
B
'); }); }); @@ -342,7 +355,7 @@ describe('parse5-utils', () => { const document = ''; const result = utils.appendToDocument(document, '
Hello world
'); if (!result) throw new Error(); - expect(result).to.equal('
Hello world
'); + assert.equal(result, '
Hello world
'); }); it('injects after other elements', () => { @@ -350,7 +363,8 @@ describe('parse5-utils', () => { ''; const result = utils.appendToDocument(document, '
Hello world
'); if (!result) throw new Error(); - expect(result).to.equal( + assert.equal( + result, '
Hello world
', ); }); @@ -359,13 +373,13 @@ describe('parse5-utils', () => { const document = ''; const result = utils.appendToDocument(document, '
Hello world
'); if (!result) throw new Error(); - expect(result).to.equal('
Hello world
'); + assert.equal(result, '
Hello world
'); }); it('returns null if there is no head or body', () => { const document = ''; const result = utils.appendToDocument(document, '
A
B
'); - expect(result).to.equal('
A
B
'); + assert.equal(result, '
A
B
'); }); }); }); diff --git a/packages/polyfills-loader/package.json b/packages/polyfills-loader/package.json index 7e5ce021ce..200600e4fb 100644 --- a/packages/polyfills-loader/package.json +++ b/packages/polyfills-loader/package.json @@ -26,9 +26,9 @@ }, "scripts": { "build": "tsc", - "test:node": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --reporter dot", + "test:node": "node --test --test-force-exit test/**/*.test.ts", "test:update-snapshots": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --update-snapshots", - "test:watch": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --watch --watch-files src,test" + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/polyfills-loader/test/createPolyfillsData.test.ts b/packages/polyfills-loader/test/createPolyfillsData.test.ts index f4eb850892..79241382cd 100644 --- a/packages/polyfills-loader/test/createPolyfillsData.test.ts +++ b/packages/polyfills-loader/test/createPolyfillsData.test.ts @@ -1,9 +1,10 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; import path from 'path'; -import { expect } from 'chai'; -import { PolyfillsLoaderConfig, PolyfillFile } from '../src/types.js'; -import { createPolyfillsData } from '../src/createPolyfillsData.js'; -import { noModuleSupportTest, fileTypes } from '../src/utils.js'; +import type { PolyfillsLoaderConfig, PolyfillFile } from '../dist/types.js'; +import { createPolyfillsData } from '../dist/createPolyfillsData.js'; +import { noModuleSupportTest, fileTypes } from '../dist/utils.js'; function cleanupPolyfill(polyfill: PolyfillFile) { if (!polyfill) { @@ -40,11 +41,11 @@ describe('polyfills', () => { const polyfillFiles = await createPolyfillsData(config); for (const p of polyfillFiles) { - expect(p.content).to.be.a('string', `Polyfill ${p.name} has no content`); + assert.equal(typeof p.content, 'string', `Polyfill ${p.name} has no content`); cleanupPolyfill(p); } - expect(polyfillFiles).to.eql([ + assert.deepEqual(polyfillFiles, [ { name: 'core-js', type: fileTypes.SCRIPT, @@ -138,11 +139,11 @@ describe('polyfills', () => { }; const polyfillFiles = await createPolyfillsData(config); for (const p of polyfillFiles) { - expect(p.content).to.be.a('string', `Polyfill ${p.name} has no content`); + assert.equal(typeof p.content, 'string', `Polyfill ${p.name} has no content`); cleanupPolyfill(p); } - expect(polyfillFiles).to.eql([ + assert.deepEqual(polyfillFiles, [ { name: 'fetch', path: 'polyfills/fetch.js', @@ -165,11 +166,11 @@ describe('polyfills', () => { const polyfillFiles = await createPolyfillsData(config); for (const p of polyfillFiles) { - expect(p.content).to.be.a('string', `Polyfill ${p.name} has no content`); + assert.equal(typeof p.content, 'string', `Polyfill ${p.name} has no content`); cleanupPolyfill(p); } - expect(polyfillFiles).to.eql([ + assert.deepEqual(polyfillFiles, [ { name: 'webcomponents-shady-css-custom-style', type: fileTypes.SCRIPT, @@ -197,11 +198,11 @@ describe('polyfills', () => { const polyfillFiles = await createPolyfillsData(config); for (const p of polyfillFiles) { - expect(p.content).to.be.a('string', `Polyfill ${p.name} has no content`); + assert.equal(typeof p.content, 'string', `Polyfill ${p.name} has no content`); cleanupPolyfill(p); } - expect(polyfillFiles).to.eql([ + assert.deepEqual(polyfillFiles, [ { name: 'systemjs', type: fileTypes.SCRIPT, @@ -232,11 +233,11 @@ describe('polyfills', () => { const polyfillFiles = await createPolyfillsData(config); for (const p of polyfillFiles) { - expect(p.content).to.be.a('string', `Polyfill ${p.name} has no content`); + assert.equal(typeof p.content, 'string', `Polyfill ${p.name} has no content`); cleanupPolyfill(p); } - expect(polyfillFiles).to.eql([ + assert.deepEqual(polyfillFiles, [ { name: 'systemjs', type: fileTypes.SCRIPT, @@ -257,11 +258,11 @@ describe('polyfills', () => { const polyfillFiles = await createPolyfillsData(config); for (const p of polyfillFiles) { - expect(p.content).to.be.a('string', `Polyfill ${p.name} has no content`); + assert.equal(typeof p.content, 'string', `Polyfill ${p.name} has no content`); cleanupPolyfill(p); } - expect(polyfillFiles).to.eql([ + assert.deepEqual(polyfillFiles, [ { name: 'systemjs', type: fileTypes.SCRIPT, @@ -277,12 +278,12 @@ describe('polyfills', () => { name: 'polyfill-a', test: "'foo' in window", content: '', - path: path.resolve(__dirname, 'custom-polyfills/polyfill-a.js'), + path: path.resolve(import.meta.dirname, 'custom-polyfills/polyfill-a.js'), }, { name: 'polyfill-b', content: '', - path: path.resolve(__dirname, 'custom-polyfills/polyfill-b.js'), + path: path.resolve(import.meta.dirname, 'custom-polyfills/polyfill-b.js'), }, ]; @@ -300,11 +301,11 @@ describe('polyfills', () => { const polyfillFiles = await createPolyfillsData(config); for (const p of polyfillFiles) { - expect(p.content).to.be.a('string', `Polyfill ${p.name} has no content`); + assert.equal(typeof p.content, 'string', `Polyfill ${p.name} has no content`); cleanupPolyfill(p); } - expect(polyfillFiles).to.eql([ + assert.deepEqual(polyfillFiles, [ { name: 'core-js', type: fileTypes.SCRIPT, @@ -338,11 +339,11 @@ describe('polyfills', () => { const polyfillFiles = await createPolyfillsData(config); for (const p of polyfillFiles) { - expect(p.content).to.be.a('string', `Polyfill ${p.name} has no content`); + assert.equal(typeof p.content, 'string', `Polyfill ${p.name} has no content`); cleanupPolyfill(p); } - expect(polyfillFiles).to.eql([ + assert.deepEqual(polyfillFiles, [ { name: 'systemjs', type: fileTypes.SCRIPT, diff --git a/packages/polyfills-loader/test/createPolyfillsLoader.test.ts b/packages/polyfills-loader/test/createPolyfillsLoader.test.ts index d77e6ecb05..d5561ea5af 100644 --- a/packages/polyfills-loader/test/createPolyfillsLoader.test.ts +++ b/packages/polyfills-loader/test/createPolyfillsLoader.test.ts @@ -1,9 +1,10 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; import fs from 'fs'; import path from 'path'; -import { PolyfillsLoaderConfig } from '../src/types.js'; -import { createPolyfillsLoader } from '../src/createPolyfillsLoader.js'; -import { noModuleSupportTest, fileTypes } from '../src/utils.js'; +import type { PolyfillsLoaderConfig } from '../dist/types.js'; +import { createPolyfillsLoader } from '../dist/createPolyfillsLoader.js'; +import { noModuleSupportTest, fileTypes } from '../dist/utils.js'; const updateSnapshots = process.argv.includes('--update-snapshots'); @@ -14,26 +15,31 @@ interface TestSnapshotArgs { } async function testSnapshot({ name, config, expectedFiles = [] }: TestSnapshotArgs) { - const snapshotPath = path.join(__dirname, 'snapshots', 'createPolyfillsLoader', `${name}.js`); + const snapshotPath = path.join( + import.meta.dirname, + 'snapshots', + 'createPolyfillsLoader', + `${name}.js`, + ); const loader = await createPolyfillsLoader(config); if (!loader) { throw new Error('No loader was generated'); } - expect(loader.polyfillFiles.map(f => f.path)).to.eql(expectedFiles); + assert.deepEqual( + loader.polyfillFiles.map(f => f.path), + expectedFiles, + ); if (updateSnapshots) { fs.writeFileSync(snapshotPath, loader.code, 'utf-8'); } else { const snapshot = fs.readFileSync(snapshotPath, 'utf-8'); - expect(loader.code.trim()).to.equal(snapshot.trim()); + assert.equal(loader.code.trim(), snapshot.trim()); } } -describe('createPolyfillsLoader', function describe() { - // bootup of the first test can take a long time in CI to load all the polyfills - this.timeout(5000); - +describe('createPolyfillsLoader', { timeout: 5000 }, () => { it('generates a loader script with one module resource', async () => { await testSnapshot({ name: 'module-resource', diff --git a/packages/polyfills-loader/test/injectPolyfillsLoader.test.ts b/packages/polyfills-loader/test/injectPolyfillsLoader.test.ts index 5d1ba0560a..ddad39b9c8 100644 --- a/packages/polyfills-loader/test/injectPolyfillsLoader.test.ts +++ b/packages/polyfills-loader/test/injectPolyfillsLoader.test.ts @@ -1,9 +1,10 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; import path from 'path'; import fs from 'fs'; -import { injectPolyfillsLoader } from '../src/injectPolyfillsLoader.js'; -import { noModuleSupportTest, fileTypes } from '../src/utils.js'; -import { PolyfillsLoaderConfig } from '../src/types.js'; +import { injectPolyfillsLoader } from '../dist/injectPolyfillsLoader.js'; +import { noModuleSupportTest, fileTypes } from '../dist/utils.js'; +import type { PolyfillsLoaderConfig } from '../dist/types.js'; const updateSnapshots = process.argv.includes('--update-snapshots'); @@ -15,14 +16,19 @@ const defaultConfig = { }; async function testSnapshot(name: string, htmlString: string, config: PolyfillsLoaderConfig) { - const snapshotPath = path.join(__dirname, 'snapshots', 'injectPolyfillsLoader', `${name}.html`); + const snapshotPath = path.join( + import.meta.dirname, + 'snapshots', + 'injectPolyfillsLoader', + `${name}.html`, + ); const result = await injectPolyfillsLoader(htmlString, config); if (updateSnapshots) { fs.writeFileSync(snapshotPath, result.htmlString, 'utf-8'); } else { const snapshot = fs.readFileSync(snapshotPath, 'utf-8'); - expect(result.htmlString.trim()).to.equal(snapshot.trim()); + assert.equal(result.htmlString.trim(), snapshot.trim()); } } diff --git a/packages/rollup-plugin-copy/package.json b/packages/rollup-plugin-copy/package.json index ee1b7935a9..1d25b2836f 100644 --- a/packages/rollup-plugin-copy/package.json +++ b/packages/rollup-plugin-copy/package.json @@ -29,8 +29,8 @@ "node": ">=22.0.0" }, "scripts": { - "test:node": "mocha test/**/*.test.js --reporter dot", - "test:watch": "mocha test/**/*.test.js --watch --watch-files src,test --reporter dot" + "test:node": "node --test --test-force-exit test/**/*.test.js", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.js" }, "files": [ "*.d.ts", diff --git a/packages/rollup-plugin-copy/test/integration.test.js b/packages/rollup-plugin-copy/test/integration.test.js index c4e5900d98..840d9b19e9 100644 --- a/packages/rollup-plugin-copy/test/integration.test.js +++ b/packages/rollup-plugin-copy/test/integration.test.js @@ -1,5 +1,6 @@ +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); const path = require('path'); -const { expect } = require('chai'); const rollup = require('rollup'); const { copy } = require('../src/copy.js'); @@ -12,12 +13,11 @@ describe('rollup-plugin-copy', () => { }); const { output } = await bundle.generate({ format: 'es' }); - expect(output.length).to.equal(5); - expect(output.map(x => x.fileName).filter(x => x.endsWith('.svg'))).to.have.members([ - 'a.svg', - 'b.svg', - `sub${path.sep}sub-a.svg`, - `sub${path.sep}sub-b.mark.svg`, - ]); + assert.equal(output.length, 5); + const svgFiles = output.map(x => x.fileName).filter(x => x.endsWith('.svg')); + assert.deepEqual( + svgFiles.sort(), + ['a.svg', 'b.svg', `sub${path.sep}sub-a.svg`, `sub${path.sep}sub-b.mark.svg`].sort(), + ); }); }); diff --git a/packages/rollup-plugin-copy/test/listFiles.test.js b/packages/rollup-plugin-copy/test/listFiles.test.js index c51a771231..06f2f7cae1 100644 --- a/packages/rollup-plugin-copy/test/listFiles.test.js +++ b/packages/rollup-plugin-copy/test/listFiles.test.js @@ -1,32 +1,36 @@ +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); const path = require('path'); -const { expect } = require('chai'); const { listFiles } = require('../src/listFiles.js'); describe('listFiles', () => { it('gives a list of files', async () => { const files = await listFiles('*.svg', path.resolve(__dirname, './fixture/')); - expect(files.length).to.equal(2); - expect(files).to.have.members([ - path.join(__dirname, './fixture/a.svg'), - path.join(__dirname, './fixture/b.svg'), - ]); + assert.equal(files.length, 2); + assert.deepEqual( + files.sort(), + [path.join(__dirname, './fixture/a.svg'), path.join(__dirname, './fixture/b.svg')].sort(), + ); }); it('only gives files and no folders', async () => { const files = await listFiles('**/*.svg', path.resolve(__dirname, './fixture/')); - expect(files.length).to.equal(4); - expect(files).to.have.members([ - path.join(__dirname, './fixture/a.svg'), - path.join(__dirname, './fixture/b.svg'), - path.join(__dirname, './fixture/sub/sub-b.mark.svg'), - path.join(__dirname, './fixture/sub/sub-a.svg'), - ]); + assert.equal(files.length, 4); + assert.deepEqual( + files.sort(), + [ + path.join(__dirname, './fixture/a.svg'), + path.join(__dirname, './fixture/b.svg'), + path.join(__dirname, './fixture/sub/sub-b.mark.svg'), + path.join(__dirname, './fixture/sub/sub-a.svg'), + ].sort(), + ); }); it('will copy files inside dot folders', async () => { const files = await listFiles('**/*.svg', path.resolve(__dirname, './fixtureDot/')); - expect(files.length).to.equal(1); - expect(files[0]).to.match(/fixtureDot(\/|\\)\.folder(\/|\\)inside-dot-folder\.svg$/); + assert.equal(files.length, 1); + assert.match(files[0], /fixtureDot(\/|\\)\.folder(\/|\\)inside-dot-folder\.svg$/); }); }); diff --git a/packages/rollup-plugin-copy/test/patternsToFiles.test.js b/packages/rollup-plugin-copy/test/patternsToFiles.test.js index c681efe945..d61d1d5b09 100644 --- a/packages/rollup-plugin-copy/test/patternsToFiles.test.js +++ b/packages/rollup-plugin-copy/test/patternsToFiles.test.js @@ -1,16 +1,17 @@ +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); const path = require('path'); -const { expect } = require('chai'); const { patternsToFiles } = require('../src/patternsToFiles.js'); describe('patternsToFiles', () => { it('works with a string', async () => { const files = await patternsToFiles('*.svg', path.resolve(__dirname, './fixture/')); - expect(files.length).to.equal(2); - expect(files).to.have.members([ - path.join(__dirname, './fixture/a.svg'), - path.join(__dirname, './fixture/b.svg'), - ]); + assert.equal(files.length, 2); + assert.deepEqual( + files.sort(), + [path.join(__dirname, './fixture/a.svg'), path.join(__dirname, './fixture/b.svg')].sort(), + ); }); it('works with an array of strings ', async () => { @@ -18,11 +19,14 @@ describe('patternsToFiles', () => { ['*.svg', 'sub/*.mark.svg'], path.resolve(__dirname, './fixture/'), ); - expect(files.length).to.equal(3); - expect(files).to.have.members([ - path.join(__dirname, './fixture/a.svg'), - path.join(__dirname, './fixture/b.svg'), - path.join(__dirname, './fixture/sub/sub-b.mark.svg'), - ]); + assert.equal(files.length, 3); + assert.deepEqual( + files.sort(), + [ + path.join(__dirname, './fixture/a.svg'), + path.join(__dirname, './fixture/b.svg'), + path.join(__dirname, './fixture/sub/sub-b.mark.svg'), + ].sort(), + ); }); }); diff --git a/packages/rollup-plugin-html/package.json b/packages/rollup-plugin-html/package.json index a3a5807e51..1fbba00a96 100644 --- a/packages/rollup-plugin-html/package.json +++ b/packages/rollup-plugin-html/package.json @@ -28,8 +28,8 @@ "demo:mpa": "rm -rf demo/dist && rollup -c demo/mpa/rollup.config.js --watch & npm run serve-demo", "demo:spa": "rm -rf demo/dist && rollup -c demo/spa/rollup.config.js --watch & npm run serve-demo", "serve-demo": "node ../dev-server/dist/bin.js --watch --root-dir demo/dist --app-index index.html --compatibility none --open", - "test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", - "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.js", diff --git a/packages/rollup-plugin-html/test/rollup-plugin-html.test.ts b/packages/rollup-plugin-html/test/rollup-plugin-html.test.ts index b9f0aa45c7..5c6cc5b825 100644 --- a/packages/rollup-plugin-html/test/rollup-plugin-html.test.ts +++ b/packages/rollup-plugin-html/test/rollup-plugin-html.test.ts @@ -1,7 +1,9 @@ -import { rollup, OutputChunk, OutputOptions, Plugin } from 'rollup'; -import { expect } from 'chai'; +import { rollup } from 'rollup'; +import type { OutputChunk, OutputOptions, Plugin } from 'rollup'; +import assert from 'node:assert/strict'; +import { describe, it, afterEach } from 'node:test'; import path from 'path'; -import { rollupPluginHTML } from '../src/index.js'; +import { rollupPluginHTML } from '../dist/index.js'; import { html, css, @@ -66,21 +68,24 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(3); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(chunks['entrypoint-a.js']).to.include(js`console.log('entrypoint-a.js');`); - expect(chunks['entrypoint-b.js']).to.include(js`console.log('entrypoint-b.js');`); - - expect(assets['index.html']).to.equal(html` - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 3); + assert.equal(Object.keys(assets).length, 1); + + assert.ok(chunks['entrypoint-a.js'].includes(js`console.log('entrypoint-a.js');`)); + assert.ok(chunks['entrypoint-b.js'].includes(js`console.log('entrypoint-b.js');`)); + + assert.equal( + assets['index.html'], + html` + + + + + + + + `, + ); }); it('can build with html file as rollup input', async () => { @@ -123,21 +128,24 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(3); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(chunks['entrypoint-a.js']).to.include(js`console.log('entrypoint-a.js');`); - expect(chunks['entrypoint-b.js']).to.include(js`console.log('entrypoint-b.js');`); - - expect(assets['index.html']).to.equal(html` - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 3); + assert.equal(Object.keys(assets).length, 1); + + assert.ok(chunks['entrypoint-a.js'].includes(js`console.log('entrypoint-a.js');`)); + assert.ok(chunks['entrypoint-b.js'].includes(js`console.log('entrypoint-b.js');`)); + + assert.equal( + assets['index.html'], + html` + + + + + + + + `, + ); }); it('will retain attributes on script tags', async () => { @@ -180,21 +188,24 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(3); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(chunks['entrypoint-a.js']).to.include(js`console.log('entrypoint-a.js');`); - expect(chunks['entrypoint-b.js']).to.include(js`console.log('entrypoint-b.js');`); - - expect(assets['index.html']).to.equal(html` - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 3); + assert.equal(Object.keys(assets).length, 1); + + assert.ok(chunks['entrypoint-a.js'].includes(js`console.log('entrypoint-a.js');`)); + assert.ok(chunks['entrypoint-b.js'].includes(js`console.log('entrypoint-b.js');`)); + + assert.equal( + assets['index.html'], + html` + + + + + + + + `, + ); }); it('can build with pure html file as rollup input', async () => { @@ -217,17 +228,20 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(assets['index.html']).to.equal(html` - - - -

hello world

- - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); + + assert.equal( + assets['index.html'], + html` + + + +

hello world

+ + + `, + ); }); it('can build with multiple pure html inputs', async () => { @@ -262,26 +276,32 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(2); - - expect(assets['index1.html']).to.equal(html` - - - -

hello world

- - - `); - - expect(assets['index2.html']).to.equal(html` - - - -

hey there

- - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 2); + + assert.equal( + assets['index1.html'], + html` + + + +

hello world

+ + + `, + ); + + assert.equal( + assets['index2.html'], + html` + + + +

hey there

+ + + `, + ); }); it('can build with html string as input', async () => { @@ -306,17 +326,20 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(assets['index.html']).to.equal(html` - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); + + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); }); it('resolves paths relative to virtual html filename', async () => { @@ -341,17 +364,20 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(assets['nested/index.html']).to.equal(html` - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); + + assert.equal( + assets['nested/index.html'], + html` + + + + + + + `, + ); }); it('can build with inline modules', async () => { @@ -376,21 +402,24 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); const hash = '16165cb387fc14ed1fe1749d05f19f7b'; - expect(chunks[`inline-module-${hash}.js`]).to.include(js`console.log('app.js');`); + assert.ok(chunks[`inline-module-${hash}.js`].includes(js`console.log('app.js');`)); - expect(assets['index.html']).to.equal(html` - - - - - - - `); + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); }); it('resolves inline module imports relative to the HTML file', async () => { @@ -422,11 +451,11 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); const hash = 'b774aefb8bf002b291fd54d27694a34d'; - expect(chunks[`inline-module-${hash}.js`]).to.include(js`console.log('app.js');`); + assert.ok(chunks[`inline-module-${hash}.js`].includes(js`console.log('app.js');`)); }); it('can build transforming final output', async () => { @@ -453,18 +482,21 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(assets['index.html']).to.equal(html` - - - -

Goodbye world

- - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); + + assert.equal( + assets['index.html'], + html` + + + +

Goodbye world

+ + + + `, + ); }); it('can build with a public path', async () => { @@ -489,17 +521,20 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(assets['index.html']).to.equal(html` - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); + + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); }); it('can build with a public path with a file in a directory', async () => { @@ -525,17 +560,20 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(assets['nested/index.html']).to.equal(html` - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); + + assert.equal( + assets['nested/index.html'], + html` + + + + + + + `, + ); }); it('can build with multiple build outputs', async () => { @@ -579,28 +617,31 @@ describe('rollup-plugin-html', () => { const { chunks: chunksA, assets: assetsA } = await bundleA; const { chunks: chunksB, assets: assetsB } = await bundleB; - expect(Object.keys(chunksA)).to.have.lengthOf(1); - expect(Object.keys(assetsA)).to.have.lengthOf(0); - expect(Object.keys(chunksB)).to.have.lengthOf(1); - expect(Object.keys(assetsB)).to.have.lengthOf(1); - - expect(chunksA['app.js']).to.include(js`console.log('app.js');`); - expect(chunksA['app.js']).to.include(js`console.log('module.js');`); - expect(chunksB['app.js']).to.include(js`console.log('app.js');`); - expect(chunksB['app.js']).to.include(js`console.log('module.js');`); - - expect(assetsA['index.html']).to.not.exist; - expect(assetsB['index.html']).to.equal(html` - - - - - - - - `); + assert.equal(Object.keys(chunksA).length, 1); + assert.equal(Object.keys(assetsA).length, 0); + assert.equal(Object.keys(chunksB).length, 1); + assert.equal(Object.keys(assetsB).length, 1); + + assert.ok(chunksA['app.js'].includes(js`console.log('app.js');`)); + assert.ok(chunksA['app.js'].includes(js`console.log('module.js');`)); + assert.ok(chunksB['app.js'].includes(js`console.log('app.js');`)); + assert.ok(chunksB['app.js'].includes(js`console.log('module.js');`)); + + assert.equal(assetsA['index.html'], undefined); + assert.equal( + assetsB['index.html'], + html` + + + + + + + + `, + ); }); it('can build with index.html as input and an extra html file as output', async () => { @@ -631,28 +672,34 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(2); - expect(Object.keys(assets)).to.have.lengthOf(2); - - expect(chunks['app.js']).to.exist; - - expect(assets['index.html']).to.equal(html` - - - - - - - `); - - expect(assets['foo.html']).to.equal(html` - - - -

foo.html

- - - `); + assert.equal(Object.keys(chunks).length, 2); + assert.equal(Object.keys(assets).length, 2); + + assert.ok(chunks['app.js']); + + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); + + assert.equal( + assets['foo.html'], + html` + + + +

foo.html

+ + + `, + ); }); it('can build with multiple html inputs', async () => { @@ -711,42 +758,51 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(4); - expect(Object.keys(assets)).to.have.lengthOf(3); - - expect(chunks['entrypoint-a.js']).to.exist; - expect(chunks['entrypoint-b.js']).to.exist; - expect(chunks['entrypoint-c.js']).to.exist; - - expect(assets['page-a.html']).to.equal(html` - - - -

Page A

- - - - `); - - expect(assets['page-b.html']).to.equal(html` - - - -

Page B

- - - - `); - - expect(assets['page-c.html']).to.equal(html` - - - -

Page C

- - - - `); + assert.equal(Object.keys(chunks).length, 4); + assert.equal(Object.keys(assets).length, 3); + + assert.ok(chunks['entrypoint-a.js']); + assert.ok(chunks['entrypoint-b.js']); + assert.ok(chunks['entrypoint-c.js']); + + assert.equal( + assets['page-a.html'], + html` + + + +

Page A

+ + + + `, + ); + + assert.equal( + assets['page-b.html'], + html` + + + +

Page B

+ + + + `, + ); + + assert.equal( + assets['page-c.html'], + html` + + + +

Page C

+ + + + `, + ); }); it('can use a glob to build multiple pages', async () => { @@ -804,46 +860,55 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(4); - expect(Object.keys(assets)).to.have.lengthOf(3); - - expect(chunks['page-a.js']).to.exist; - expect(chunks['page-b.js']).to.exist; - expect(chunks['page-c.js']).to.exist; - - expect(assets['page-a.html']).to.equal(html` - - - -

page-a.html

- - - - - `); - - expect(assets['page-b.html']).to.equal(html` - - - -

page-b.html

- - - - - `); + assert.equal(Object.keys(chunks).length, 4); + assert.equal(Object.keys(assets).length, 3); + + assert.ok(chunks['page-a.js']); + assert.ok(chunks['page-b.js']); + assert.ok(chunks['page-c.js']); + + assert.equal( + assets['page-a.html'], + html` + + + +

page-a.html

+ + + + + `, + ); + + assert.equal( + assets['page-b.html'], + html` + + + +

page-b.html

+ + + + + `, + ); // TODO: investigate why shared.js is after page-c.js here but before in the others - expect(assets['page-c.html']).to.equal(html` - - - -

page-c.html

- - - - - `); + assert.equal( + assets['page-c.html'], + html` + + + +

page-c.html

+ + + + + `, + ); }); it('can exclude globs', async () => { @@ -865,10 +930,10 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); - expect(assets).to.have.keys(['index.html']); + assert.deepEqual(Object.keys(assets).sort(), ['index.html'].sort()); }); it('creates unique inline script names', async () => { @@ -898,42 +963,60 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(3); - expect(Object.keys(assets)).to.have.lengthOf(3); - - expect(chunks['inline-module-d463148d1d5869e52917a3b270db9e72.js']).to.exist; - expect(chunks['inline-module-b81da853430abdf130bcc7c4d0ade6d9.js']).to.exist; - expect(chunks['inline-module-170bb2146da66c440259138c7e0fea7e.js']).to.exist; - - expect(assets['nestedA/indexA.html']).to.equal(html` - - - -

Page A

- - - - `); - - expect(assets['nestedB/indexB.html']).to.equal(html` - - - -

Page B

- - - - `); - - expect(assets['indexC.html']).to.equal(html` - - - -

Page C

- - - - `); + assert.equal(Object.keys(chunks).length, 3); + assert.equal(Object.keys(assets).length, 3); + + assert.ok(chunks['inline-module-d463148d1d5869e52917a3b270db9e72.js']); + assert.ok(chunks['inline-module-b81da853430abdf130bcc7c4d0ade6d9.js']); + assert.ok(chunks['inline-module-170bb2146da66c440259138c7e0fea7e.js']); + + assert.equal( + assets['nestedA/indexA.html'], + html` + + + +

Page A

+ + + + `, + ); + + assert.equal( + assets['nestedB/indexB.html'], + html` + + + +

Page B

+ + + + `, + ); + + assert.equal( + assets['indexC.html'], + html` + + + +

Page C

+ + + + `, + ); }); it('deduplicates common modules', async () => { @@ -964,40 +1047,58 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(3); - - expect(chunks['inline-module-44281cf3dede62434e0dd368df08902f.js']).to.exist; - - expect(assets['a.html']).to.equal(html` - - - -

Page A

- - - - `); - - expect(assets['b.html']).to.equal(html` - - - -

Page B

- - - - `); - - expect(assets['c.html']).to.equal(html` - - - -

Page C

- - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 3); + + assert.ok(chunks['inline-module-44281cf3dede62434e0dd368df08902f.js']); + + assert.equal( + assets['a.html'], + html` + + + +

Page A

+ + + + `, + ); + + assert.equal( + assets['b.html'], + html` + + + +

Page B

+ + + + `, + ); + + assert.equal( + assets['c.html'], + html` + + + +

Page C

+ + + + `, + ); }); it('outputs the hashed entrypoint name', async () => { @@ -1024,8 +1125,8 @@ describe('rollup-plugin-html', () => { entryFileNames: '[name]-[hash].js', }); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); const appChunk = output.find(f => // @ts-ignore @@ -1033,17 +1134,20 @@ describe('rollup-plugin-html', () => { ) as OutputChunk; // ensure it's actually hashed - expect(appChunk.fileName).to.not.equal('app.js'); + assert.notEqual(appChunk.fileName, 'app.js'); // get hashed name dynamically - expect(assets['index.html']).to.equal(html` - - - - - - - `); + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); }); it('outputs import path relative to the final output html', async () => { @@ -1068,22 +1172,25 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(assets['nested/index.html']).to.equal(html` - - - - - - - `); - }); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); - it('can change HTML root directory', async () => { - const rootDir = createApp({ - 'different-root/src/app.js': js` + assert.equal( + assets['nested/index.html'], + html` + + + + + + + `, + ); + }); + + it('can change HTML root directory', async () => { + const rootDir = createApp({ + 'different-root/src/app.js': js` console.log('app.js'); `, }); @@ -1103,17 +1210,20 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(assets['src/nested/index.html']).to.equal(html` - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); + + assert.equal( + assets['src/nested/index.html'], + html` + + + + + + + `, + ); }); it('can get the input with getInputs()', async () => { @@ -1145,9 +1255,9 @@ describe('rollup-plugin-html', () => { await rollup({ plugins: [pluginB] }); await rollup({ plugins: [pluginC] }); - expect(pluginA.api.getInputs()[0].name).to.equal('index.html'); - expect(pluginB.api.getInputs()[0].name).to.equal('my-page.html'); - expect(pluginC.api.getInputs()[0].name).to.equal('nested/my-other-page.html'); + assert.equal(pluginA.api.getInputs()[0].name, 'index.html'); + assert.equal(pluginB.api.getInputs()[0].name, 'my-page.html'); + assert.equal(pluginC.api.getInputs()[0].name, 'nested/my-other-page.html'); }); it('supports other plugins injecting a transform function', async () => { @@ -1209,22 +1319,25 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(3); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(chunks['entrypoint-a.js']).to.include(js`console.log('entrypoint-a.js');`); - expect(chunks['entrypoint-b.js']).to.include(js`console.log('entrypoint-b.js');`); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 3); + assert.equal(Object.keys(assets).length, 1); + + assert.ok(chunks['entrypoint-a.js'].includes(js`console.log('entrypoint-a.js');`)); + assert.ok(chunks['entrypoint-b.js'].includes(js`console.log('entrypoint-b.js');`)); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + `, + ); }); it('includes referenced assets in the bundle', async () => { @@ -1286,43 +1399,49 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(11); - - expect(assets).to.have.keys([ - 'assets/image-a-XOCPHCrV.png', - 'assets/image-b-BgQHKcRn.png', - 'assets/image-c-C4yLPiIL.png', - 'assets/image-a-BCCvKrTe.svg', - 'assets/image-b-C4stzVZW.svg', - 'assets/image-c-DPeYetg3.svg', - 'assets/styles-Bh7Pnjui.css', - 'assets/x-DDGg8O6h.css', - 'assets/y-DJTrnPH3.css', - 'assets/webmanifest-BkrOR1WG.json', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - - - - - -
- -
- - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 11); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/image-a-XOCPHCrV.png', + 'assets/image-b-BgQHKcRn.png', + 'assets/image-c-C4yLPiIL.png', + 'assets/image-a-BCCvKrTe.svg', + 'assets/image-b-C4stzVZW.svg', + 'assets/image-c-DPeYetg3.svg', + 'assets/styles-Bh7Pnjui.css', + 'assets/x-DDGg8O6h.css', + 'assets/y-DJTrnPH3.css', + 'assets/webmanifest-BkrOR1WG.json', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + + + + + +
+ +
+ + + `, + ); }); it('[legacy] includes referenced assets in the bundle', async () => { @@ -1383,41 +1502,47 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(10); - - expect(assets).to.have.keys([ - 'assets/image-a.png', - 'assets/image-b.png', - 'assets/image-c-C4yLPiIL.png', - 'assets/image-a.svg', - 'assets/image-b-C4stzVZW.svg', - 'assets/styles-Bh7Pnjui.css', - 'assets/x-DDGg8O6h.css', - 'assets/y-DJTrnPH3.css', - 'assets/webmanifest.json', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - - - - -
- -
- - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 10); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/image-a.png', + 'assets/image-b.png', + 'assets/image-c-C4yLPiIL.png', + 'assets/image-a.svg', + 'assets/image-b-C4stzVZW.svg', + 'assets/styles-Bh7Pnjui.css', + 'assets/x-DDGg8O6h.css', + 'assets/y-DJTrnPH3.css', + 'assets/webmanifest.json', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + + + + +
+ +
+ + + `, + ); }); it('does not deduplicate static assets with similar names', async () => { @@ -1447,24 +1572,26 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(3); - - expect(assets).to.have.keys([ - 'assets/foo-BCCvKrTe.svg', - 'assets/foo-C4stzVZW.svg', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 3); + + assert.deepEqual( + Object.keys(assets).sort(), + ['assets/foo-BCCvKrTe.svg', 'assets/foo-C4stzVZW.svg', 'index.html'].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + `, + ); }); it('[legacy] deduplicates static assets with similar names', async () => { @@ -1495,20 +1622,26 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(3); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 3); - expect(assets).to.have.keys(['assets/foo.svg', 'assets/foo1.svg', 'index.html']); + assert.deepEqual( + Object.keys(assets).sort(), + ['assets/foo.svg', 'assets/foo1.svg', 'index.html'].sort(), + ); - expect(assets['index.html']).to.equal(html` - - - - - - - - `); + assert.equal( + assets['index.html'], + html` + + + + + + + + `, + ); }); it('[legacy] static and hashed asset nodes can reference the same files', async () => { @@ -1538,21 +1671,27 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(3); - - expect(assets).to.have.keys(['assets/foo.svg', 'assets/foo-BCCvKrTe.svg', 'index.html']); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 3); + + assert.deepEqual( + Object.keys(assets).sort(), + ['assets/foo.svg', 'assets/foo-BCCvKrTe.svg', 'index.html'].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + `, + ); }); it('deduplicates common assets', async () => { @@ -1582,21 +1721,27 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(2); - - expect(assets).to.have.keys(['assets/image-a-XOCPHCrV.png', 'index.html']); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 2); + + assert.deepEqual( + Object.keys(assets).sort(), + ['assets/image-a-XOCPHCrV.png', 'index.html'].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + `, + ); }); it('deduplicates common assets across HTML files', async () => { @@ -1648,43 +1793,50 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); - - expect(assets).to.have.keys([ - 'assets/image-a-XOCPHCrV.png', - 'page-a.html', - 'page-b.html', - 'page-c.html', - ]); - - expect(assets['page-a.html']).to.equal(html` - - - - - - - `); - - expect(assets['page-b.html']).to.equal(html` - - - - - - - `); - - expect(assets['page-c.html']).to.equal(html` - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); + + assert.deepEqual( + Object.keys(assets).sort(), + ['assets/image-a-XOCPHCrV.png', 'page-a.html', 'page-b.html', 'page-c.html'].sort(), + ); + + assert.equal( + assets['page-a.html'], + html` + + + + + + + `, + ); + + assert.equal( + assets['page-b.html'], + html` + + + + + + + `, + ); + + assert.equal( + assets['page-c.html'], + html` + + + + + + + + `, + ); }); it('can turn off extracting assets', async () => { @@ -1721,19 +1873,22 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + `, + ); }); it('can inject a CSP meta tag for inline scripts', async () => { @@ -1774,32 +1929,35 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(2); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(chunks['entrypoint-a.js']).to.include(js`console.log('entrypoint-a.js');`); - expect(chunks['entrypoint-b.js']).to.include(js`console.log('entrypoint-b.js');`); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 2); + assert.equal(Object.keys(assets).length, 1); + + assert.ok(chunks['entrypoint-a.js'].includes(js`console.log('entrypoint-a.js');`)); + assert.ok(chunks['entrypoint-b.js'].includes(js`console.log('entrypoint-b.js');`)); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + + + + `, + ); }); it('can add to an existing CSP meta tag for inline scripts', async () => { @@ -1845,32 +2003,35 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(2); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(chunks['entrypoint-a.js']).to.include(js`console.log('entrypoint-a.js');`); - expect(chunks['entrypoint-b.js']).to.include(js`console.log('entrypoint-b.js');`); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 2); + assert.equal(Object.keys(assets).length, 1); + + assert.ok(chunks['entrypoint-a.js'].includes(js`console.log('entrypoint-a.js');`)); + assert.ok(chunks['entrypoint-b.js'].includes(js`console.log('entrypoint-b.js');`)); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + + + + `, + ); }); it('can add to an existing CSP meta tag for inline scripts even if script-src is already there', async () => { @@ -1916,32 +2077,35 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(2); - expect(Object.keys(assets)).to.have.lengthOf(1); - - expect(chunks['entrypoint-a.js']).to.include(js`console.log('entrypoint-a.js');`); - expect(chunks['entrypoint-b.js']).to.include(js`console.log('entrypoint-b.js');`); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 2); + assert.equal(Object.keys(assets).length, 1); + + assert.ok(chunks['entrypoint-a.js'].includes(js`console.log('entrypoint-a.js');`)); + assert.ok(chunks['entrypoint-b.js'].includes(js`console.log('entrypoint-b.js');`)); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + + + + `, + ); }); it('can inject a service worker registration script if injectServiceWorker and serviceWorkerPath are provided', async () => { @@ -1989,14 +2153,13 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(3); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 3); - expect(assets).to.have.keys([ - 'index.html', - 'sub-with-js/index.html', - 'sub-pure-html/index.html', - ]); + assert.deepEqual( + Object.keys(assets).sort(), + ['index.html', 'sub-with-js/index.html', 'sub-pure-html/index.html'].sort(), + ); function extractServiceWorkerPath(code: string) { const registerOpen = code.indexOf(".register('"); @@ -2004,11 +2167,13 @@ describe('rollup-plugin-html', () => { return code.substring(registerOpen + 11, registerClose); } - expect(extractServiceWorkerPath(assets['index.html'] as string)).to.equal('service-worker.js'); - expect(extractServiceWorkerPath(assets['sub-with-js/index.html'] as string)).to.equal( + assert.equal(extractServiceWorkerPath(assets['index.html'] as string), 'service-worker.js'); + assert.equal( + extractServiceWorkerPath(assets['sub-with-js/index.html'] as string), '../service-worker.js', ); - expect(extractServiceWorkerPath(assets['sub-pure-html/index.html'] as string)).to.equal( + assert.equal( + extractServiceWorkerPath(assets['sub-pure-html/index.html'] as string), '../service-worker.js', ); }); @@ -2050,27 +2215,33 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); - - expect(assets).to.have.keys([ - 'assets/styles-Bh7Pnjui.css', - 'assets/foo-CxmWeBHm.svg', - 'assets/image-b-C4stzVZW.svg', - 'x/index.html', - ]); - - expect(assets['x/index.html']).to.equal(html` - - - - - - - - - - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/styles-Bh7Pnjui.css', + 'assets/foo-CxmWeBHm.svg', + 'assets/image-b-C4stzVZW.svg', + 'x/index.html', + ].sort(), + ); + + assert.equal( + assets['x/index.html'], + html` + + + + + + + + + + `, + ); }); it('handles fonts linked from css files', async () => { @@ -2117,42 +2288,51 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); - - expect(assets).to.have.keys([ - 'assets/font-normal-Cht9ZB76.woff2', - 'assets/font-bold-eQjSonqH.woff2', - 'assets/styles-BRQfqhN6.css', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - `); - - expect(assets['assets/styles-BRQfqhN6.css']).to.equal(css` - @font-face { - font-family: Font; - src: url('font-normal-Cht9ZB76.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - - @font-face { - font-family: Font; - src: url('font-bold-eQjSonqH.woff2') format('woff2'); - font-weight: bold; - font-style: normal; - font-display: swap; - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/font-normal-Cht9ZB76.woff2', + 'assets/font-bold-eQjSonqH.woff2', + 'assets/styles-Dhs3ufep.css', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); + + assert.equal( + assets['assets/styles-Dhs3ufep.css'], + css` + @font-face { + font-family: Font; + src: url('font-normal-Cht9ZB76.woff2') format('woff2'); + font-weight: normal; + font-style: normal; + font-display: swap; + } + + @font-face { + font-family: Font; + src: url('font-bold-eQjSonqH.woff2') format('woff2'); + font-weight: bold; + font-style: normal; + font-display: swap; + } + `, + ); }); it('[legacy] handles fonts linked from css files', async () => { @@ -2200,42 +2380,51 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); - - expect(assets).to.have.keys([ - 'assets/assets/font-normal-Cht9ZB76.woff2', - 'assets/assets/font-bold-eQjSonqH.woff2', - 'assets/styles-BUBaODov.css', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - `); - - expect(assets['assets/styles-BUBaODov.css']).to.equal(css` - @font-face { - font-family: Font; - src: url('assets/font-normal-Cht9ZB76.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - - @font-face { - font-family: Font; - src: url('assets/font-bold-eQjSonqH.woff2') format('woff2'); - font-weight: bold; - font-style: normal; - font-display: swap; - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/assets/font-normal-Cht9ZB76.woff2', + 'assets/assets/font-bold-eQjSonqH.woff2', + 'assets/styles-BUBaODov.css', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); + + assert.equal( + assets['assets/styles-BUBaODov.css'], + css` + @font-face { + font-family: Font; + src: url('assets/font-normal-Cht9ZB76.woff2') format('woff2'); + font-weight: normal; + font-style: normal; + font-display: swap; + } + + @font-face { + font-family: Font; + src: url('assets/font-bold-eQjSonqH.woff2') format('woff2'); + font-weight: bold; + font-style: normal; + font-display: swap; + } + `, + ); }); it('handles fonts linked from css files in node_modules', async () => { @@ -2282,53 +2471,62 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); - - expect(assets).to.have.keys([ - 'assets/font-normal-Cht9ZB76.woff2', - 'assets/font-bold-eQjSonqH.woff2', - 'assets/styles-BRQfqhN6.css', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - `); - - expect(assets['assets/styles-BRQfqhN6.css']).to.equal(css` - @font-face { - font-family: Font; - src: url('font-normal-Cht9ZB76.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - - @font-face { - font-family: Font; - src: url('font-bold-eQjSonqH.woff2') format('woff2'); - font-weight: bold; - font-style: normal; - font-display: swap; - } - `); - }); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/font-normal-Cht9ZB76.woff2', + 'assets/font-bold-eQjSonqH.woff2', + 'assets/styles-Dhs3ufep.css', + 'index.html', + ].sort(), + ); - it('[legacy] handles fonts linked from css files in node_modules', async () => { - const rootDir = createApp({ - 'node_modules/foo/fonts/font-bold.woff2': 'font-bold', - 'node_modules/foo/fonts/font-normal.woff2': 'font-normal', - 'node_modules/foo/styles.css': css` - @font-face { - font-family: Font; - src: url('fonts/font-normal.woff2') format('woff2'); - font-weight: normal; + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); + + assert.equal( + assets['assets/styles-Dhs3ufep.css'], + css` + @font-face { + font-family: Font; + src: url('font-normal-Cht9ZB76.woff2') format('woff2'); + font-weight: normal; + font-style: normal; + font-display: swap; + } + + @font-face { + font-family: Font; + src: url('font-bold-eQjSonqH.woff2') format('woff2'); + font-weight: bold; + font-style: normal; + font-display: swap; + } + `, + ); + }); + + it('[legacy] handles fonts linked from css files in node_modules', async () => { + const rootDir = createApp({ + 'node_modules/foo/fonts/font-bold.woff2': 'font-bold', + 'node_modules/foo/fonts/font-normal.woff2': 'font-normal', + 'node_modules/foo/styles.css': css` + @font-face { + font-family: Font; + src: url('fonts/font-normal.woff2') format('woff2'); + font-weight: normal; font-style: normal; font-display: swap; } @@ -2365,42 +2563,51 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); - - expect(assets).to.have.keys([ - 'assets/assets/font-normal-Cht9ZB76.woff2', - 'assets/assets/font-bold-eQjSonqH.woff2', - 'assets/styles-BUBaODov.css', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - `); - - expect(assets['assets/styles-BUBaODov.css']).to.equal(css` - @font-face { - font-family: Font; - src: url('assets/font-normal-Cht9ZB76.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - - @font-face { - font-family: Font; - src: url('assets/font-bold-eQjSonqH.woff2') format('woff2'); - font-weight: bold; - font-style: normal; - font-display: swap; - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/assets/font-normal-Cht9ZB76.woff2', + 'assets/assets/font-bold-eQjSonqH.woff2', + 'assets/styles-BUBaODov.css', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); + + assert.equal( + assets['assets/styles-BUBaODov.css'], + css` + @font-face { + font-family: Font; + src: url('assets/font-normal-Cht9ZB76.woff2') format('woff2'); + font-weight: normal; + font-style: normal; + font-display: swap; + } + + @font-face { + font-family: Font; + src: url('assets/font-bold-eQjSonqH.woff2') format('woff2'); + font-weight: bold; + font-style: normal; + font-display: swap; + } + `, + ); }); it('handles duplicate fonts correctly', async () => { @@ -2448,45 +2655,57 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); - - expect(assets).to.have.keys([ - 'assets/font-normal-Cht9ZB76.woff2', - 'assets/styles-a-CKKhzbId.css', - 'assets/styles-b-DdUNHRx0.css', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - - `); - - expect(assets['assets/styles-a-CKKhzbId.css']).to.equal(css` - @font-face { - font-family: Font; - src: url('font-normal-Cht9ZB76.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - `); - - expect(assets['assets/styles-b-DdUNHRx0.css']).to.equal(css` - @font-face { - font-family: Font2; - src: url('font-normal-Cht9ZB76.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/font-normal-Cht9ZB76.woff2', + 'assets/styles-a-jFIfrzm8.css', + 'assets/styles-b-B-8m1N7T.css', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + `, + ); + + assert.equal( + assets['assets/styles-a-jFIfrzm8.css'], + css` + @font-face { + font-family: Font; + src: url('font-normal-Cht9ZB76.woff2') format('woff2'); + font-weight: normal; + font-style: normal; + font-display: swap; + } + `, + ); + + assert.equal( + assets['assets/styles-b-B-8m1N7T.css'], + css` + @font-face { + font-family: Font2; + src: url('font-normal-Cht9ZB76.woff2') format('woff2'); + font-weight: normal; + font-style: normal; + font-display: swap; + } + `, + ); }); it('handles images referenced from css', async () => { @@ -2554,63 +2773,72 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(9); - - expect(assets).to.have.keys([ - 'assets/star-D_LO5feX.avif', - 'assets/star-BKg9qmmf.gif', - 'assets/star-BZWqL7hS.jpeg', - 'assets/star-Df0JryvN.jpg', - 'assets/star-CXig10q7.png', - 'assets/star-CwhgM_z4.svg', - 'assets/star-CKbh5mKn.webp', - 'assets/styles-DgHxUupJ.css', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - `); - - expect(assets['assets/styles-DgHxUupJ.css']).to.equal(css` - #a { - background-image: url('star-D_LO5feX.avif'); - } - - #b { - background-image: url('star-BKg9qmmf.gif'); - } - - #c { - background-image: url('star-BZWqL7hS.jpeg'); - } - - #d { - background-image: url('star-Df0JryvN.jpg'); - } - - #e { - background-image: url('star-CXig10q7.png'); - } - - #f { - background-image: url('star-CwhgM_z4.svg'); - } - - #g { - background-image: url('star-CwhgM_z4.svg#foo'); - } - - #h { - background-image: url('star-CKbh5mKn.webp'); - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 9); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/star-D_LO5feX.avif', + 'assets/star-BKg9qmmf.gif', + 'assets/star-BZWqL7hS.jpeg', + 'assets/star-Df0JryvN.jpg', + 'assets/star-CXig10q7.png', + 'assets/star-CwhgM_z4.svg', + 'assets/star-CKbh5mKn.webp', + 'assets/styles-mywkihBc.css', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); + + assert.equal( + assets['assets/styles-mywkihBc.css'], + css` + #a { + background-image: url('star-D_LO5feX.avif'); + } + + #b { + background-image: url('star-BKg9qmmf.gif'); + } + + #c { + background-image: url('star-BZWqL7hS.jpeg'); + } + + #d { + background-image: url('star-Df0JryvN.jpg'); + } + + #e { + background-image: url('star-CXig10q7.png'); + } + + #f { + background-image: url('star-CwhgM_z4.svg'); + } + + #g { + background-image: url('star-CwhgM_z4.svg#foo'); + } + + #h { + background-image: url('star-CKbh5mKn.webp'); + } + `, + ); }); it('[legacy] handles images referenced from css', async () => { @@ -2679,63 +2907,72 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(9); - - expect(assets).to.have.keys([ - 'assets/assets/star-D_LO5feX.avif', - 'assets/assets/star-BKg9qmmf.gif', - 'assets/assets/star-BZWqL7hS.jpeg', - 'assets/assets/star-Df0JryvN.jpg', - 'assets/assets/star-CXig10q7.png', - 'assets/assets/star-CwhgM_z4.svg', - 'assets/assets/star-CKbh5mKn.webp', - 'assets/styles-Cuqf3qRf.css', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - `); - - expect(assets['assets/styles-Cuqf3qRf.css']).to.equal(css` - #a { - background-image: url('assets/star-D_LO5feX.avif'); - } - - #b { - background-image: url('assets/star-BKg9qmmf.gif'); - } - - #c { - background-image: url('assets/star-BZWqL7hS.jpeg'); - } - - #d { - background-image: url('assets/star-Df0JryvN.jpg'); - } - - #e { - background-image: url('assets/star-CXig10q7.png'); - } - - #f { - background-image: url('assets/star-CwhgM_z4.svg'); - } - - #g { - background-image: url('assets/star-CwhgM_z4.svg#foo'); - } - - #h { - background-image: url('assets/star-CKbh5mKn.webp'); - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 9); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/assets/star-D_LO5feX.avif', + 'assets/assets/star-BKg9qmmf.gif', + 'assets/assets/star-BZWqL7hS.jpeg', + 'assets/assets/star-Df0JryvN.jpg', + 'assets/assets/star-CXig10q7.png', + 'assets/assets/star-CwhgM_z4.svg', + 'assets/assets/star-CKbh5mKn.webp', + 'assets/styles-Cuqf3qRf.css', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); + + assert.equal( + assets['assets/styles-Cuqf3qRf.css'], + css` + #a { + background-image: url('assets/star-D_LO5feX.avif'); + } + + #b { + background-image: url('assets/star-BKg9qmmf.gif'); + } + + #c { + background-image: url('assets/star-BZWqL7hS.jpeg'); + } + + #d { + background-image: url('assets/star-Df0JryvN.jpg'); + } + + #e { + background-image: url('assets/star-CXig10q7.png'); + } + + #f { + background-image: url('assets/star-CwhgM_z4.svg'); + } + + #g { + background-image: url('assets/star-CwhgM_z4.svg#foo'); + } + + #h { + background-image: url('assets/star-CKbh5mKn.webp'); + } + `, + ); }); it('allows to exclude external assets usign a glob pattern', async () => { @@ -2808,55 +3045,64 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(5); - - expect(assets).to.have.keys([ - 'assets/image-a-XOCPHCrV.png', - 'assets/image-b-BgQHKcRn.png', - 'assets/styles-pLj9D-P3.css', - 'assets/webmanifest-BkrOR1WG.json', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - - - - - -
- -
- - - `); - - expect(assets['assets/styles-pLj9D-P3.css']).to.equal(css` - #a1 { - background-image: url('image-a-XOCPHCrV.png'); - } - - #a2 { - background-image: url('image-a.svg'); - } - - #d1 { - background-image: url('image-b-BgQHKcRn.png'); - } - - #d2 { - background-image: url('./image-b.svg'); - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 5); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/image-a-XOCPHCrV.png', + 'assets/image-b-BgQHKcRn.png', + 'assets/styles-Bv-4gk2N.css', + 'assets/webmanifest-BkrOR1WG.json', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + + + + + +
+ +
+ + + `, + ); + + assert.equal( + assets['assets/styles-Bv-4gk2N.css'], + css` + #a1 { + background-image: url('image-a-XOCPHCrV.png'); + } + + #a2 { + background-image: url('image-a.svg'); + } + + #d1 { + background-image: url('image-b-BgQHKcRn.png'); + } + + #d2 { + background-image: url('./image-b.svg'); + } + `, + ); }); it('[legacy] allows to exclude external assets usign a glob pattern', async () => { @@ -2930,57 +3176,66 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(7); - - expect(assets).to.have.keys([ - 'assets/assets/image-a-XOCPHCrV.png', - 'assets/assets/image-b-BgQHKcRn.png', - 'assets/image-a.png', - 'assets/image-b.png', - 'assets/styles-DFIb0lB5.css', - 'assets/webmanifest.json', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - - - - - -
- -
- - - `); - - expect(assets['assets/styles-DFIb0lB5.css']).to.equal(css` - #a1 { - background-image: url('assets/image-a-XOCPHCrV.png'); - } - - #a2 { - background-image: url('image-a.svg'); - } - - #d1 { - background-image: url('assets/image-b-BgQHKcRn.png'); - } - - #d2 { - background-image: url('./image-b.svg'); - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 7); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'assets/assets/image-a-XOCPHCrV.png', + 'assets/assets/image-b-BgQHKcRn.png', + 'assets/image-a.png', + 'assets/image-b.png', + 'assets/styles-DFIb0lB5.css', + 'assets/webmanifest.json', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + + + + + +
+ +
+ + + `, + ); + + assert.equal( + assets['assets/styles-DFIb0lB5.css'], + css` + #a1 { + background-image: url('assets/image-a-XOCPHCrV.png'); + } + + #a2 { + background-image: url('image-a.svg'); + } + + #d1 { + background-image: url('assets/image-b-BgQHKcRn.png'); + } + + #d2 { + background-image: url('./image-b.svg'); + } + `, + ); }); it('rewrites paths according to assetFileNames', async () => { @@ -3039,50 +3294,62 @@ describe('rollup-plugin-html', () => { assetFileNames: 'static/[name].immutable.[hash][extname]', }); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(5); - - expect(assets).to.have.keys([ - 'static/font.immutable.C5MNjX-h.woff2', - 'static/global.immutable.BRYeVgdd.css', - 'static/image.immutable.7xJLr_7N.png', - 'static/styles.immutable.exe7_Vpw.css', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - - - `); - - expect(assets['static/global.immutable.BRYeVgdd.css']).to.equal(css` - @font-face { - font-family: Font; - src: url('font.immutable.C5MNjX-h.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - `); - - expect(assets['static/styles.immutable.exe7_Vpw.css']).to.equal(css` - #a { - background-image: url('image.immutable.7xJLr_7N.png'); - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 5); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'static/font.immutable.C5MNjX-h.woff2', + 'static/global.immutable.DB0fKkjs.css', + 'static/image.immutable.7xJLr_7N.png', + 'static/styles.immutable.D4tZXVv0.css', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + + + `, + ); + + assert.equal( + assets['static/global.immutable.DB0fKkjs.css'], + css` + @font-face { + font-family: Font; + src: url('font.immutable.C5MNjX-h.woff2') format('woff2'); + font-weight: normal; + font-style: normal; + font-display: swap; + } + `, + ); + + assert.equal( + assets['static/styles.immutable.D4tZXVv0.css'], + css` + #a { + background-image: url('image.immutable.7xJLr_7N.png'); + } + `, + ); }); it('resolves paths by using publicPath when assetFileNames puts assets in different dirs', async () => { @@ -3152,50 +3419,62 @@ describe('rollup-plugin-html', () => { }, }); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(5); - - expect(assets).to.have.keys([ - 'fonts/font.immutable.C5MNjX-h.woff2', - 'styles/global.immutable.CIo7MOhV.css', - 'images/image.immutable.7xJLr_7N.png', - 'styles/styles.immutable.BxCpevuY.css', - 'index.html', - ]); - - expect(assets['index.html']).to.equal(html` - - - - - - - - - - - `); - - expect(assets['styles/global.immutable.CIo7MOhV.css']).to.equal(css` - @font-face { - font-family: Font; - src: url('/static/fonts/font.immutable.C5MNjX-h.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - `); - - expect(assets['styles/styles.immutable.BxCpevuY.css']).to.equal(css` - #a { - background-image: url('/static/images/image.immutable.7xJLr_7N.png'); - } - `); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 5); + + assert.deepEqual( + Object.keys(assets).sort(), + [ + 'fonts/font.immutable.C5MNjX-h.woff2', + 'styles/global.immutable.B3Q0ucg4.css', + 'images/image.immutable.7xJLr_7N.png', + 'styles/styles.immutable.C3Z0Fs2-.css', + 'index.html', + ].sort(), + ); + + assert.equal( + assets['index.html'], + html` + + + + + + + + + + + `, + ); + + assert.equal( + assets['styles/global.immutable.B3Q0ucg4.css'], + css` + @font-face { + font-family: Font; + src: url('/static/fonts/font.immutable.C5MNjX-h.woff2') format('woff2'); + font-weight: normal; + font-style: normal; + font-display: swap; + } + `, + ); + + assert.equal( + assets['styles/styles.immutable.C3Z0Fs2-.css'], + css` + #a { + background-image: url('/static/images/image.immutable.7xJLr_7N.png'); + } + `, + ); }); it('can minify extracted CSS', async () => { @@ -3229,21 +3508,27 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets, assetsUnformatted } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(2); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 2); - expect(assets).to.have.keys(['assets/styles-DPU2l-t7.css', 'index.html']); + assert.deepEqual( + Object.keys(assets).sort(), + ['assets/styles-DPU2l-t7.css', 'index.html'].sort(), + ); - expect(assets['index.html']).to.equal(html` - - - - - - - `); + assert.equal( + assets['index.html'], + html` + + + + + + + `, + ); - expect(assetsUnformatted['assets/styles-DPU2l-t7.css']).to.equal('p{font-weight:700}'); + assert.equal(assetsUnformatted['assets/styles-DPU2l-t7.css'], 'p{font-weight:700}'); }); it('can bundle extracted CSS', async () => { @@ -3288,507 +3573,39 @@ describe('rollup-plugin-html', () => { const build = await rollup(config); const { chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(2); - - expect(assets).to.have.keys(['assets/styles-Dc1pq4Qu.css', 'index.html']); - - expect(assets['index.html']).to.equal(html` - - - - - - - `); - - expect(assets['assets/styles-Dc1pq4Qu.css']).to.equal(css` - body { - background-color: #fff; - } - - @media (prefers-color-scheme: dark) { - body { - background-color: #000; - } - } - `); - }); - - it('can transform assets in CSS', async () => { - const rootDir = createApp({ - 'bg-image.png': 'bg-image.png', - 'styles.css': css` - div { - background-image: url('./bg-image.png'); - } - `, - }); - - const config = { - plugins: [ - rollupPluginHTML({ - rootDir, - input: { - html: html` - - - - - - - `, - }, - transformAsset: (content, filePath) => { - if (filePath.endsWith('.png')) { - return Buffer.from('bg-image-transformed.png'); - } - return content; - }, - }), - ], - }; - - const build = await rollup(config); - const { chunks, assets } = await generateTestBundle(build, outputConfig); - - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(3); - - expect(assets).to.have.keys([ - 'assets/bg-image-B8JuQo5R.png', - 'assets/styles-Brz3za0w.css', - 'index.html', - ]); - - expect(assets['assets/bg-image-B8JuQo5R.png']).to.equal('bg-image-transformed.png'); - }); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 2); - it('transforms asset only once for the same file in same CSS and other CSS files', async () => { - const rootDir = createApp({ - 'filters.svg': 'filters.svg', - 'design-system.css': css` - .blur { - filter: url('filters.svg#blur'); - } + assert.deepEqual( + Object.keys(assets).sort(), + ['assets/styles-Dc1pq4Qu.css', 'index.html'].sort(), + ); - .sepia { - filter: url('filters.svg#sepia'); - } - `, - 'styles.css': css` - .content { - filter: url('filters.svg#outline'); - } + assert.equal( + assets['index.html'], + html` + + + + + + `, - }); - - let countTransformAssetCalls = 0; - - const config = { - plugins: [ - rollupPluginHTML({ - rootDir, - input: { - html: html` - - - - - - - - `, - }, - transformAsset: (content, filePath) => { - if (filePath.endsWith('.svg')) { - countTransformAssetCalls++; - return Buffer.from('filters-transformed.svg'); - } - return content; - }, - }), - ], - }; - - const build = await rollup(config); - const { chunks, assets } = await generateTestBundle(build, outputConfig); - - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); - - expect(assets).to.have.keys([ - 'assets/filters-BNeK3QVf.svg', - 'assets/design-system-DznFRd92.css', - 'assets/styles-CWG_g22Q.css', - 'index.html', - ]); - - expect(countTransformAssetCalls).to.equal(1); - }); - - it('recalculates the hash of the CSS output filename when it references the file that changed the content', async () => { - const indexHtml = html` - - - - - - - `; - - const stylesCss = css` - @font-face { - font-family: Font; - src: url('fonts/font.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - `; - - const rootDir1 = createApp({ - 'fonts/font.woff2': 'font', - 'styles.css': stylesCss, - }); - - const rootDir2 = createApp({ - 'fonts/font.woff2': 'font-changed', - 'styles.css': stylesCss, - }); - - const config1 = { - plugins: [ - rollupPluginHTML({ - rootDir: rootDir1, - input: { - html: indexHtml, - }, - }), - ], - }; - - const config2 = { - plugins: [ - rollupPluginHTML({ - rootDir: rootDir2, - input: { - html: indexHtml, - }, - }), - ], - }; - - const build1 = await rollup(config1); - const build2 = await rollup(config2); - const bundle1 = await generateTestBundle(build1, { - ...outputConfig, - assetFileNames: '[hash][extname]', - }); - const bundle2 = await generateTestBundle(build2, { - ...outputConfig, - assetFileNames: '[hash][extname]', - }); - - const output1StylesName = Object.keys(bundle1.assets).find(name => name.endsWith('.css'))!; - const output2StylesName = Object.keys(bundle2.assets).find(name => name.endsWith('.css'))!; - - expect(output1StylesName).to.not.equal(output2StylesName); - }); - - it('recalculates the hash of the CSS output filename when it references the same file which was transformed', async () => { - const createSameApp = () => - createApp({ - 'index.html': html` - - - - - - - `, - 'fonts/font.woff2': 'font', - 'styles.css': css` - @font-face { - font-family: Font; - src: url('fonts/font.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - `, - }); - - const rootDir1 = createSameApp(); - const rootDir2 = createSameApp(); - - const config1 = { - plugins: [ - rollupPluginHTML({ - rootDir: rootDir1, - input: './index.html', - }), - ], - }; - - const config2 = { - plugins: [ - rollupPluginHTML({ - rootDir: rootDir2, - input: './index.html', - transformAsset: (content, filePath) => { - if (filePath.endsWith('.woff2')) { - return Buffer.from('font-transformed'); - } - return content; - }, - }), - ], - }; - - const build1 = await rollup(config1); - const build2 = await rollup(config2); - const bundle1 = await generateTestBundle(build1, { - ...outputConfig, - assetFileNames: '[hash][extname]', - }); - const bundle2 = await generateTestBundle(build2, { - ...outputConfig, - assetFileNames: '[hash][extname]', - }); - - const output1StylesName = Object.keys(bundle1.assets).find(name => name.endsWith('.css'))!; - const output2StylesName = Object.keys(bundle2.assets).find(name => name.endsWith('.css'))!; - - expect(output1StylesName).to.not.equal(output2StylesName); - }); - - it('recalculates the hash of the CSS output filename when it references the file that is moved in the output', async () => { - const createSameApp = () => - createApp({ - 'index.html': html` - - - - - - - `, - 'fonts/font.woff2': 'font', - 'styles.css': css` - @font-face { - font-family: Font; - src: url('fonts/font.woff2') format('woff2'); - font-weight: normal; - font-style: normal; - font-display: swap; - } - `, - }); - - const rootDir1 = createSameApp(); - const rootDir2 = createSameApp(); - - const config1 = { - plugins: [ - rollupPluginHTML({ - rootDir: rootDir1, - input: './index.html', - }), - ], - }; - - const config2 = { - plugins: [ - rollupPluginHTML({ - rootDir: rootDir2, - input: './index.html', - }), - ], - }; - - const build1 = await rollup(config1); - const build2 = await rollup(config2); - const bundle1 = await generateTestBundle(build1, { - ...outputConfig, - assetFileNames: '[hash][extname]', - }); - const bundle2 = await generateTestBundle(build2, { - ...outputConfig, - assetFileNames: asset => { - if (asset.name?.endsWith('.woff2')) { - return 'moved/[hash][extname]'; - } - return '[hash][extname]'; - }, - }); - - const output1StylesName = Object.keys(bundle1.assets).find(name => name.endsWith('.css'))!; - const output2StylesName = Object.keys(bundle2.assets).find(name => name.endsWith('.css'))!; - - expect(output1StylesName).to.not.equal(output2StylesName); - }); - - describe('preserved output paths', () => { - it('resolves relative paths', async () => { - const rootDir = createApp({ - 'assets/icons/arrow.svg': '', - 'fonts/font.woff2': 'font-data', - 'styles/main.css': css` - @font-face { - font-family: Font; - src: url('../fonts/font.woff2') format('woff2'); - } - - .arrow { - background: url('../assets/icons/arrow.svg'); - } - `, - 'styles/components/button.css': css` - .button { - background: url('../../assets/icons/arrow.svg'); - } - `, - }); - - const config = { - plugins: [ - rollupPluginHTML({ - rootDir, - input: { - html: html` - - - - - - - - `, - }, - }), - ], - }; - - const build = await rollup(config); - const { assets } = await generateTestBundle(build, { - ...outputConfig, - assetFileNames: (asset: { originalFileNames: string[] }) => - path.relative(rootDir, asset.originalFileNames[0]).split(path.sep).join('/'), - }); - - expect(assets['styles/main.css']).to.equal(css` - @font-face { - font-family: Font; - src: url('../fonts/font.woff2') format('woff2'); - } - - .arrow { - background: url('../assets/icons/arrow.svg'); - } - `); + ); - expect(assets['styles/components/button.css']).to.equal(css` - .button { - background: url('../../assets/icons/arrow.svg'); + assert.equal( + assets['assets/styles-Dc1pq4Qu.css'], + css` + body { + background-color: #fff; } - `); - }); - it('handles CSS files with SVG fragments (#icon)', async () => { - const rootDir = createApp({ - 'assets/sprite.svg': '', - 'styles.css': css` - .icon { - background: url('assets/sprite.svg#icon'); - } - `, - }); - - const config = { - plugins: [ - rollupPluginHTML({ - rootDir, - input: { - html: html` - - - - - - - `, - }, - }), - ], - }; - - const build = await rollup(config); - const { assets } = await generateTestBundle(build, { - ...outputConfig, - assetFileNames: (asset: { originalFileNames: string[] }) => - path.relative(rootDir, asset.originalFileNames[0]).split(path.sep).join('/'), - }); - - expect(assets['styles.css']).to.equal(css` - .icon { - background: url('assets/sprite.svg#icon'); - } - `); - }); - - it('handles multiple CSS files referencing the same asset', async () => { - const rootDir = createApp({ - 'shared/image.png': 'image-data', - 'styles/a.css': css` - .a { - background: url('../shared/image.png'); - } - `, - 'styles/nested/b.css': css` - .b { - background: url('../../shared/image.png'); + @media (prefers-color-scheme: dark) { + body { + background-color: #000; } - `, - }); - - const config = { - plugins: [ - rollupPluginHTML({ - rootDir, - input: { - html: html` - - - - - - - - `, - }, - }), - ], - }; - - const build = await rollup(config); - const { assets } = await generateTestBundle(build, { - ...outputConfig, - assetFileNames: (asset: { originalFileNames: string[] }) => - path.relative(rootDir, asset.originalFileNames[0]).split(path.sep).join('/'), - }); - - expect(assets['styles/a.css']).to.equal(css` - .a { - background: url('../shared/image.png'); - } - `); - - expect(assets['styles/nested/b.css']).to.equal(css` - .b { - background: url('../../shared/image.png'); } - `); - }); + `, + ); }); }); diff --git a/packages/rollup-plugin-html/test/src/input/InputData.test.ts b/packages/rollup-plugin-html/test/src/input/InputData.test.ts index 9810a5dfa6..9c7cb92c43 100644 --- a/packages/rollup-plugin-html/test/src/input/InputData.test.ts +++ b/packages/rollup-plugin-html/test/src/input/InputData.test.ts @@ -1,9 +1,10 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it, afterEach } from 'node:test'; import path from 'path'; import { cleanApp, createApp, html, js } from '../../../../../test-utils/rollup-test-utils.js'; -import { getInputData } from '../../../src/input/getInputData.js'; -import { InputData } from '../../../src/input/InputData.js'; +import { getInputData } from '../../../dist/input/getInputData.js'; +import type { InputData } from '../../../dist/input/InputData.js'; function cleanupHtml(str: string) { return str.replace(/(\r\n|\n|\r| )/gm, ''); @@ -37,7 +38,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ input: 'index.html', rootDir }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'index.html'), html: '

Helloworld

', @@ -64,7 +65,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ input: { path: 'index.html' }, rootDir }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'index.html'), html: '

Helloworld

', @@ -91,7 +92,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ input: { path: 'index.html', name: 'foo.html' }, rootDir }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'index.html'), html: '

Helloworld

', @@ -128,7 +129,7 @@ describe('getInputData()', () => { input: [{ path: 'index.html' }, { path: 'not-index.html' }], rootDir, }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'index.html'), html: '

Helloworld

', @@ -163,7 +164,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ input: 'src/index.html', rootDir }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'src/index.html'), html: '

Helloworld

', @@ -190,7 +191,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ rootDir }, 'index.html'); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'index.html'), html: '

Helloworld

', @@ -217,7 +218,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ rootDir }, ['index.html']); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'index.html'), html: '

Helloworld

', @@ -251,7 +252,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ rootDir }, ['index.html', 'not-index.html']); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'index.html'), html: '

Helloworld

', @@ -296,7 +297,7 @@ describe('getInputData()', () => { { rootDir }, { 'a.html': 'index.html', 'b.html': 'not-index.html' }, ); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'index.html'), html: '

Helloworld

', @@ -338,7 +339,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ input: 'index.html', rootDir }, 'not-index.html'); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'index.html'), html: '

Helloworld

', @@ -369,7 +370,7 @@ describe('getInputData()', () => { }, rootDir, }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: undefined, html: '

HTMLasstring

', @@ -413,7 +414,7 @@ describe('getInputData()', () => { }, ], }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: undefined, html: '

HTML1

', @@ -476,7 +477,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ input: 'pages/**/*.html', rootDir }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'pages', 'page-c.html'), html: '

page-c.html

', @@ -556,7 +557,7 @@ describe('getInputData()', () => { `, }); const result = getInputData({ input: 'pages/**/*.html', flattenOutput: false, rootDir }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: path.join(rootDir, 'pages', 'page-c.html'), html: '

page-c.html

', @@ -607,7 +608,7 @@ describe('getInputData()', () => { `, }, }); - expect(cleanupResult(result)).to.eql([ + assert.deepEqual(cleanupResult(result), [ { filePath: undefined, html: '

pureHTML

', @@ -621,6 +622,6 @@ describe('getInputData()', () => { it('throws when no files or html is given', () => { const rootDir = createApp({}); - expect(() => getInputData({ rootDir })).to.throw(); + assert.throws(() => getInputData({ rootDir })); }); }); diff --git a/packages/rollup-plugin-html/test/src/input/extract/extractAssets.test.ts b/packages/rollup-plugin-html/test/src/input/extract/extractAssets.test.ts index e4abcf640c..1a573eef2a 100644 --- a/packages/rollup-plugin-html/test/src/input/extract/extractAssets.test.ts +++ b/packages/rollup-plugin-html/test/src/input/extract/extractAssets.test.ts @@ -1,7 +1,8 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it, afterEach } from 'node:test'; import { parse } from 'parse5'; import path from 'path'; -import { extractAssets } from '../../../../src/input/extract/extractAssets.js'; +import { extractAssets } from '../../../../dist/input/extract/extractAssets.js'; import { html, css, @@ -59,7 +60,7 @@ describe('extractAssets', () => { }); const assetsWithoutcontent = assets.map(a => ({ ...a, content: undefined })); - expect(assetsWithoutcontent).to.eql([ + assert.deepEqual(assetsWithoutcontent, [ { content: undefined, filePath: path.join(rootDir, 'image-a.png'), @@ -141,7 +142,7 @@ describe('extractAssets', () => { ...asset, content: asset.content.toString('utf-8').replace(/\s/g, ''), })); - expect(transformedAssets).to.eql([ + assert.deepEqual(transformedAssets, [ { content: '{"message":"helloworld"}', filePath: path.join(rootDir, 'webmanifest.json'), @@ -195,11 +196,11 @@ describe('extractAssets', () => { extractAssets: true, }); - expect(assets.length).to.equal(2); - expect(assets[0].filePath).to.equal(path.join(rootDir, 'foo', 'x.css')); - expect(assets[1].filePath).to.equal(path.join(rootDir, 'foo', 'bar', 'y.css')); - expect(assets[0].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:x;}'); - expect(assets[1].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:y;}'); + assert.equal(assets.length, 2); + assert.equal(assets[0].filePath, path.join(rootDir, 'foo', 'x.css')); + assert.equal(assets[1].filePath, path.join(rootDir, 'foo', 'bar', 'y.css')); + assert.equal(assets[0].content.toString('utf-8').replace(/\s/g, ''), ':root{color:x;}'); + assert.equal(assets[1].content.toString('utf-8').replace(/\s/g, ''), ':root{color:y;}'); }); it('resolves relative to HTML file location', () => { @@ -232,11 +233,11 @@ describe('extractAssets', () => { extractAssets: true, }); - expect(assets.length).to.equal(2); - expect(assets[0].filePath).to.equal(path.join(rootDir, 'foo', 'x.css')); - expect(assets[1].filePath).to.equal(path.join(rootDir, 'styles.css')); - expect(assets[0].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:x;}'); - expect(assets[1].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:blue;}'); + assert.equal(assets.length, 2); + assert.equal(assets[0].filePath, path.join(rootDir, 'foo', 'x.css')); + assert.equal(assets[1].filePath, path.join(rootDir, 'styles.css')); + assert.equal(assets[0].content.toString('utf-8').replace(/\s/g, ''), ':root{color:x;}'); + assert.equal(assets[1].content.toString('utf-8').replace(/\s/g, ''), ':root{color:blue;}'); }); it('resolves absolute paths relative to root dir', () => { @@ -269,11 +270,11 @@ describe('extractAssets', () => { extractAssets: true, }); - expect(assets.length).to.equal(2); - expect(assets[0].filePath).to.equal(path.join(rootDir, 'foo', 'x.css')); - expect(assets[1].filePath).to.equal(path.join(rootDir, 'styles.css')); - expect(assets[0].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:x;}'); - expect(assets[1].content.toString('utf-8').replace(/\s/g, '')).to.equal(':root{color:blue;}'); + assert.equal(assets.length, 2); + assert.equal(assets[0].filePath, path.join(rootDir, 'foo', 'x.css')); + assert.equal(assets[1].filePath, path.join(rootDir, 'styles.css')); + assert.equal(assets[0].content.toString('utf-8').replace(/\s/g, ''), ':root{color:x;}'); + assert.equal(assets[1].content.toString('utf-8').replace(/\s/g, ''), ':root{color:blue;}'); }); it('can deduplicate assets with same names', () => { @@ -297,9 +298,9 @@ describe('extractAssets', () => { extractAssets: true, }); - expect(assets.length).to.equal(1); + assert.equal(assets.length, 1); const assetsWithoutcontent = assets.map(a => ({ ...a, content: undefined })); - expect(assetsWithoutcontent).to.eql([ + assert.deepEqual(assetsWithoutcontent, [ { content: undefined, filePath: path.join(rootDir, 'image-a.png'), @@ -326,7 +327,7 @@ describe('extractAssets', () => { extractAssets: true, }); - expect(assets.length).to.equal(0); + assert.equal(assets.length, 0); }); it('does treat non module script tags as assets', () => { @@ -349,9 +350,9 @@ describe('extractAssets', () => { extractAssets: true, }); - expect(assets.length).to.equal(1); - expect(assets[0].filePath).to.equal(path.join(rootDir, 'no-module.js')); - expect(assets[0].content.toString('utf-8')).to.equal('/* no module script file */\n'); + assert.equal(assets.length, 1); + assert.equal(assets[0].filePath, path.join(rootDir, 'no-module.js')); + assert.equal(assets[0].content.toString('utf-8'), '/* no module script file */\n'); }); it('handles a picture tag using source tags with srcset', () => { @@ -398,10 +399,10 @@ describe('extractAssets', () => { }); // the src is not the same as the small jpeg image - expect(assets.length).to.equal(4); - expect(assets[0].filePath).to.equal(path.join(rootDir, 'images', 'eb26e6ca-30.avif')); - expect(assets[1].filePath).to.equal(path.join(rootDir, 'images', 'eb26e6ca-60.avif')); - expect(assets[2].filePath).to.equal(path.join(rootDir, 'images', 'eb26e6ca-30.jpeg')); - expect(assets[3].filePath).to.equal(path.join(rootDir, 'images', 'eb26e6ca-60.jpeg')); + assert.equal(assets.length, 4); + assert.equal(assets[0].filePath, path.join(rootDir, 'images', 'eb26e6ca-30.avif')); + assert.equal(assets[1].filePath, path.join(rootDir, 'images', 'eb26e6ca-60.avif')); + assert.equal(assets[2].filePath, path.join(rootDir, 'images', 'eb26e6ca-30.jpeg')); + assert.equal(assets[3].filePath, path.join(rootDir, 'images', 'eb26e6ca-60.jpeg')); }); }); diff --git a/packages/rollup-plugin-html/test/src/input/extract/extractModules.test.ts b/packages/rollup-plugin-html/test/src/input/extract/extractModules.test.ts index 1ce06c93ee..f4eb104a43 100644 --- a/packages/rollup-plugin-html/test/src/input/extract/extractModules.test.ts +++ b/packages/rollup-plugin-html/test/src/input/extract/extractModules.test.ts @@ -1,10 +1,11 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import path from 'path'; import { parse, serialize } from 'parse5'; -import { expect } from 'chai'; import { html, js } from '../../../../../../test-utils/rollup-test-utils.js'; -import { extractModules } from '../../../../src/input/extract/extractModules.js'; -import { ScriptModuleTag } from '../../../../src/RollupPluginHTMLOptions.js'; +import { extractModules } from '../../../../dist/input/extract/extractModules.js'; +import type { ScriptModuleTag } from '../../../../dist/RollupPluginHTMLOptions.js'; const { sep } = path; @@ -31,20 +32,23 @@ describe('extractModules()', () => { }); const htmlWithoutModules = serialize(document); - expect(inlineModules.length).to.equal(0); - expect(moduleImports).to.eql([ + assert.equal(inlineModules.length, 0); + assert.deepEqual(moduleImports, [ { importPath: `${sep}foo.js`, attributes: [] }, { importPath: `${sep}bar.js`, attributes: [] }, ]); - expect(html`${htmlWithoutModules}`).to.eql(html` - - - -
before
-
after
- - - `); + assert.deepEqual( + html`${htmlWithoutModules}`, + html` + + + +
before
+
after
+ + + `, + ); }); it('does not touch non module scripts', () => { @@ -62,19 +66,22 @@ describe('extractModules()', () => { }); const htmlWithoutModules = serialize(document); - expect(inlineModules.length).to.equal(0); - expect(moduleImports).to.eql([]); - expect(html`${htmlWithoutModules}`).to.eql(html` - - - -
before
- - -
after
- - - `); + assert.equal(inlineModules.length, 0); + assert.deepEqual(moduleImports, []); + assert.deepEqual( + html`${htmlWithoutModules}`, + html` + + + +
before
+ + +
after
+ + + `, + ); }); it('resolves imports relative to the root dir', () => { @@ -92,20 +99,23 @@ describe('extractModules()', () => { }); const htmlWithoutModules = serialize(document); - expect(inlineModules.length).to.equal(0); - expect(moduleImports).to.eql([ + assert.equal(inlineModules.length, 0); + assert.deepEqual(moduleImports, [ { importPath: `${sep}foo.js`, attributes: [] }, { importPath: `${sep}base${sep}bar.js`, attributes: [] }, ]); - expect(html`${htmlWithoutModules}`).to.eql(html` - - - -
before
-
after
- - - `); + assert.deepEqual( + html`${htmlWithoutModules}`, + html` + + + +
before
+
after
+ + + `, + ); }); it('resolves relative imports relative to the relative import base', () => { @@ -123,20 +133,23 @@ describe('extractModules()', () => { }); const htmlWithoutModules = serialize(document); - expect(inlineModules.length).to.equal(0); - expect(moduleImports).to.eql([ + assert.equal(inlineModules.length, 0); + assert.deepEqual(moduleImports, [ { importPath: `${sep}base-1${sep}base-2${sep}foo.js`, attributes: [] }, { importPath: `${sep}base-1${sep}bar.js`, attributes: [] }, ]); - expect(html`${htmlWithoutModules}`).to.eql(html` - - - -
before
-
after
- - - `); + assert.deepEqual( + html`${htmlWithoutModules}`, + html` + + + +
before
+
after
+ + + `, + ); }); it('extracts all inline modules from a html document', () => { @@ -158,7 +171,7 @@ describe('extractModules()', () => { }); const htmlWithoutModules = serialize(document); - expect(cleanupInlineModules(inlineModules)).to.eql([ + assert.deepEqual(cleanupInlineModules(inlineModules), [ { importPath: '/inline-module-80efb22c2d1ce27c40eae10611f7680f.js', code: js`/* my module 1 */`, @@ -170,16 +183,19 @@ describe('extractModules()', () => { attributes: [], }, ]); - expect(moduleImports).to.eql([]); - expect(html`${htmlWithoutModules}`).to.eql(html` - - - -
before
-
after
- - - `); + assert.deepEqual(moduleImports, []); + assert.deepEqual( + html`${htmlWithoutModules}`, + html` + + + +
before
+
after
+ + + `, + ); }); it('prefixes inline module with index.html directory', () => { @@ -201,7 +217,7 @@ describe('extractModules()', () => { }); const htmlWithoutModules = serialize(document); - expect(cleanupInlineModules(inlineModules)).to.eql([ + assert.deepEqual(cleanupInlineModules(inlineModules), [ { importPath: '/foo/bar/inline-module-80efb22c2d1ce27c40eae10611f7680f.js', code: js`/* my module 1 */`, @@ -213,16 +229,19 @@ describe('extractModules()', () => { attributes: [], }, ]); - expect(moduleImports).to.eql([]); - expect(html`${htmlWithoutModules}`).to.eql(html` - - - -
before
-
after
- - - `); + assert.deepEqual(moduleImports, []); + assert.deepEqual( + html`${htmlWithoutModules}`, + html` + + + +
before
+
after
+ + + `, + ); }); it('ignores absolute paths', () => { @@ -240,17 +259,20 @@ describe('extractModules()', () => { }); const htmlWithoutModules = serialize(document); - expect(inlineModules.length).to.equal(0); - expect(moduleImports).to.eql([{ importPath: `${sep}bar.js`, attributes: [] }]); - expect(html`${htmlWithoutModules}`).to.eql(html` - - - -
before
- -
after
- - - `); + assert.equal(inlineModules.length, 0); + assert.deepEqual(moduleImports, [{ importPath: `${sep}bar.js`, attributes: [] }]); + assert.deepEqual( + html`${htmlWithoutModules}`, + html` + + + +
before
+ +
after
+ + + `, + ); }); }); diff --git a/packages/rollup-plugin-html/test/src/output/css.test.ts b/packages/rollup-plugin-html/test/src/output/css.test.ts index bbdcbf3bad..4d9e70106e 100644 --- a/packages/rollup-plugin-html/test/src/output/css.test.ts +++ b/packages/rollup-plugin-html/test/src/output/css.test.ts @@ -1,13 +1,14 @@ -import { expect } from 'chai'; +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; import { createAssetPlaceholder, replacePlaceholders, calculateRelativePath, -} from '../../../src/output/css.js'; +} from '../../../dist/output/css.js'; describe('createAssetPlaceholder', () => { it('creates a placeholder with the given hash', () => { - expect(createAssetPlaceholder('abc123')).to.equal('__ROLLUP_ASSET_URL_abc123__'); + assert.equal(createAssetPlaceholder('abc123'), '__ROLLUP_ASSET_URL_abc123__'); }); }); @@ -16,28 +17,28 @@ describe('replacePlaceholders', () => { const css = `.foo { background: url('__ROLLUP_ASSET_URL_abc123__'); }`; const resolver = (hash: string) => (hash === 'abc123' ? '../assets/image.png' : undefined); const result = replacePlaceholders(css, resolver); - expect(result).to.equal(`.foo { background: url('../assets/image.png'); }`); + assert.equal(result, `.foo { background: url('../assets/image.png'); }`); }); it('preserves fragments after placeholder', () => { const css = `.foo { background: url('__ROLLUP_ASSET_URL_abc123__#icon'); }`; const resolver = () => '../assets/sprite.svg'; const result = replacePlaceholders(css, resolver); - expect(result).to.equal(`.foo { background: url('../assets/sprite.svg#icon'); }`); + assert.equal(result, `.foo { background: url('../assets/sprite.svg#icon'); }`); }); it('preserves query strings after placeholder', () => { const css = `.foo { src: url('__ROLLUP_ASSET_URL_abc123__?v=1.0'); }`; const resolver = () => '../fonts/font.woff2'; const result = replacePlaceholders(css, resolver); - expect(result).to.equal(`.foo { src: url('../fonts/font.woff2?v=1.0'); }`); + assert.equal(result, `.foo { src: url('../fonts/font.woff2?v=1.0'); }`); }); it('keeps placeholder when resolver returns undefined', () => { const css = `.foo { background: url('__ROLLUP_ASSET_URL_unknown__'); }`; const resolver = () => undefined; const result = replacePlaceholders(css, resolver); - expect(result).to.equal(css); + assert.equal(result, css); }); it('replaces multiple placeholders', () => { @@ -51,38 +52,41 @@ describe('replacePlaceholders', () => { return undefined; }; const result = replacePlaceholders(css, resolver); - expect(result).to.include("url('assets/image1.png')"); - expect(result).to.include("url('assets/image2.png')"); + assert.ok(result.includes("url('assets/image1.png')")); + assert.ok(result.includes("url('assets/image2.png')")); }); }); describe('calculateRelativePath', () => { it('calculates relative path for same directory', () => { - expect(calculateRelativePath('styles/main.css', 'styles/image.png')).to.equal('image.png'); + assert.equal(calculateRelativePath('styles/main.css', 'styles/image.png'), 'image.png'); }); it('calculates relative path for parent directory', () => { - expect(calculateRelativePath('styles/main.css', 'image.png')).to.equal('../image.png'); + assert.equal(calculateRelativePath('styles/main.css', 'image.png'), '../image.png'); }); it('calculates relative path for sibling directory', () => { - expect(calculateRelativePath('styles/main.css', 'assets/image.png')).to.equal( + assert.equal( + calculateRelativePath('styles/main.css', 'assets/image.png'), '../assets/image.png', ); }); it('calculates relative path for deeply nested CSS', () => { - expect( + assert.equal( calculateRelativePath('styles/components/button.css', 'assets/icons/arrow.svg'), - ).to.equal('../../assets/icons/arrow.svg'); + '../../assets/icons/arrow.svg', + ); }); it('calculates relative path when CSS is at root', () => { - expect(calculateRelativePath('main.css', 'assets/image.png')).to.equal('assets/image.png'); + assert.equal(calculateRelativePath('main.css', 'assets/image.png'), 'assets/image.png'); }); it('calculates relative path when both are deeply nested', () => { - expect(calculateRelativePath('a/b/c/style.css', 'x/y/z/image.png')).to.equal( + assert.equal( + calculateRelativePath('a/b/c/style.css', 'x/y/z/image.png'), '../../../x/y/z/image.png', ); }); diff --git a/packages/rollup-plugin-html/test/src/output/getEntrypointBundles.test.ts b/packages/rollup-plugin-html/test/src/output/getEntrypointBundles.test.ts index e7cf8d6478..43eb84985c 100644 --- a/packages/rollup-plugin-html/test/src/output/getEntrypointBundles.test.ts +++ b/packages/rollup-plugin-html/test/src/output/getEntrypointBundles.test.ts @@ -1,125 +1,146 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { getEntrypointBundles, createImportPath, -} from '../../../src/output/getEntrypointBundles.js'; -import { GeneratedBundle, ScriptModuleTag } from '../../../src/RollupPluginHTMLOptions.js'; +} from '../../../dist/output/getEntrypointBundles.js'; +import type { GeneratedBundle, ScriptModuleTag } from '../../../dist/RollupPluginHTMLOptions.js'; describe('createImportPath()', () => { it('creates a relative import path', () => { - expect( - createImportPath({ - outputDir: 'dist', - fileOutputDir: 'dist', - htmlFileName: 'index.html', - fileName: 'foo.js', - }), - ).to.equal('./foo.js'); + assert + .equal( + createImportPath({ + outputDir: 'dist', + fileOutputDir: 'dist', + htmlFileName: 'index.html', + fileName: 'foo.js', + }), + ) + .to.equal('./foo.js'); }); it('handles files output in a different directory', () => { - expect( - createImportPath({ - outputDir: 'dist', - fileOutputDir: 'dist/legacy', - htmlFileName: 'index.html', - fileName: 'foo.js', - }), - ).to.equal('./legacy/foo.js'); + assert + .equal( + createImportPath({ + outputDir: 'dist', + fileOutputDir: 'dist/legacy', + htmlFileName: 'index.html', + fileName: 'foo.js', + }), + ) + .to.equal('./legacy/foo.js'); }); it('handles directory in filename', () => { - expect( - createImportPath({ - outputDir: 'dist', - fileOutputDir: 'dist', - htmlFileName: 'index.html', - fileName: 'legacy/foo.js', - }), - ).to.equal('./legacy/foo.js'); + assert + .equal( + createImportPath({ + outputDir: 'dist', + fileOutputDir: 'dist', + htmlFileName: 'index.html', + fileName: 'legacy/foo.js', + }), + ) + .to.equal('./legacy/foo.js'); }); it('allows configuring a public path', () => { - expect( - createImportPath({ - publicPath: 'static', - outputDir: 'dist', - fileOutputDir: 'dist', - htmlFileName: 'index.html', - fileName: 'foo.js', - }), - ).to.equal('./static/foo.js'); + assert + .equal( + createImportPath({ + publicPath: 'static', + outputDir: 'dist', + fileOutputDir: 'dist', + htmlFileName: 'index.html', + fileName: 'foo.js', + }), + ) + .to.equal('./static/foo.js'); }); it('allows configuring an absolute public path', () => { - expect( - createImportPath({ - publicPath: '/static', - outputDir: 'dist', - fileOutputDir: 'dist', - htmlFileName: 'index.html', - fileName: 'foo.js', - }), - ).to.equal('/static/foo.js'); + assert + .equal( + createImportPath({ + publicPath: '/static', + outputDir: 'dist', + fileOutputDir: 'dist', + htmlFileName: 'index.html', + fileName: 'foo.js', + }), + ) + .to.equal('/static/foo.js'); }); it('allows configuring an absolute public path with just a /', () => { - expect( - createImportPath({ - publicPath: '/', - outputDir: 'dist', - fileOutputDir: 'dist', - htmlFileName: 'index.html', - fileName: 'foo.js', - }), - ).to.equal('/foo.js'); + assert + .equal( + createImportPath({ + publicPath: '/', + outputDir: 'dist', + fileOutputDir: 'dist', + htmlFileName: 'index.html', + fileName: 'foo.js', + }), + ) + .to.equal('/foo.js'); }); it('allows configuring an absolute public path with a trailing /', () => { - expect( - createImportPath({ - publicPath: '/static/public/', - outputDir: 'dist', - fileOutputDir: 'dist', - htmlFileName: 'index.html', - fileName: 'foo.js', - }), - ).to.equal('/static/public/foo.js'); + assert + .equal( + createImportPath({ + publicPath: '/static/public/', + outputDir: 'dist', + fileOutputDir: 'dist', + htmlFileName: 'index.html', + fileName: 'foo.js', + }), + ) + .to.equal('/static/public/foo.js'); }); it('respects a different output dir when configuring a public path', () => { - expect( - createImportPath({ - publicPath: '/static', - outputDir: 'dist', - fileOutputDir: 'dist/legacy', - htmlFileName: 'index.html', - fileName: 'foo.js', - }), - ).to.equal('/static/legacy/foo.js'); + assert + .equal( + createImportPath({ + publicPath: '/static', + outputDir: 'dist', + fileOutputDir: 'dist/legacy', + htmlFileName: 'index.html', + fileName: 'foo.js', + }), + ) + .to.equal('/static/legacy/foo.js'); }); it('when html is output in a directory, creates a relative path from the html file to the js file', () => { - expect( - createImportPath({ - outputDir: 'dist', - fileOutputDir: 'dist', - htmlFileName: 'pages/index.html', - fileName: 'foo.js', - }), - ).to.equal('../foo.js'); + assert + .equal( + createImportPath({ + outputDir: 'dist', + fileOutputDir: 'dist', + htmlFileName: 'pages/index.html', + fileName: 'foo.js', + }), + ) + .to.equal('../foo.js'); }); it('when html is output in a directory and absolute path is set, creates a direct path from the root to the js file', () => { - expect( - createImportPath({ - publicPath: '/static/', - outputDir: 'dist', - fileOutputDir: 'dist', - htmlFileName: 'pages/index.html', - fileName: 'foo.js', - }), - ).to.equal('/static/foo.js'); + assert + .equal( + createImportPath({ + publicPath: '/static/', + outputDir: 'dist', + fileOutputDir: 'dist', + htmlFileName: 'pages/index.html', + fileName: 'foo.js', + }), + ) + .to.equal('/static/foo.js'); }); }); @@ -155,12 +176,15 @@ describe('getEntrypointBundles()', () => { it('generates entrypoints for a simple project', async () => { const output = await getEntrypointBundles(defaultOptions); - expect(Object.keys(output).length).to.equal(1); - expect(output.default.options).to.equal(defaultBundles[0].options); - expect(output.default.bundle).to.equal(defaultBundles[0].bundle); - expect(output.default.entrypoints.length).to.equal(1); - expect(output.default.entrypoints[0].chunk).to.equal(defaultBundles[0].bundle['app.js']); - expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js']); + assert.equal(Object.keys(output).length, 1); + assert.equal(output.default.options, defaultBundles[0].options); + assert.equal(output.default.bundle, defaultBundles[0].bundle); + assert.equal(output.default.entrypoints.length, 1); + assert.equal(output.default.entrypoints[0].chunk, defaultBundles[0].bundle['app.js']); + assert.deepEqual( + output.default.entrypoints.map(e => e.importPath), + ['./app.js'], + ); }); it('does not output non-entrypoints', async () => { @@ -190,9 +214,12 @@ describe('getEntrypointBundles()', () => { ...defaultOptions, generatedBundles, }); - expect(Object.keys(output).length).to.equal(1); - expect(output.default.entrypoints.length).to.equal(1); - expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js']); + assert.equal(Object.keys(output).length, 1); + assert.equal(output.default.entrypoints.length, 1); + assert.deepEqual( + output.default.entrypoints.map(e => e.importPath), + ['./app.js'], + ); }); it('does not output non-chunks', async () => { @@ -223,9 +250,12 @@ describe('getEntrypointBundles()', () => { ...defaultOptions, generatedBundles, }); - expect(Object.keys(output).length).to.equal(1); - expect(output.default.entrypoints.length).to.equal(1); - expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js']); + assert.equal(Object.keys(output).length, 1); + assert.equal(output.default.entrypoints.length, 1); + assert.deepEqual( + output.default.entrypoints.map(e => e.importPath), + ['./app.js'], + ); }); it('matches on facadeModuleId', async () => { @@ -255,9 +285,12 @@ describe('getEntrypointBundles()', () => { ...defaultOptions, generatedBundles, }); - expect(Object.keys(output).length).to.equal(1); - expect(output.default.entrypoints.length).to.equal(1); - expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js']); + assert.equal(Object.keys(output).length, 1); + assert.equal(output.default.entrypoints.length, 1); + assert.deepEqual( + output.default.entrypoints.map(e => e.importPath), + ['./app.js'], + ); }); it('returns all entrypoints when no input module ids are given', async () => { @@ -294,9 +327,12 @@ describe('getEntrypointBundles()', () => { inputModuleIds, generatedBundles, }); - expect(Object.keys(output).length).to.equal(1); - expect(output.default.entrypoints.length).to.equal(2); - expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js', './not-app.js']); + assert.equal(Object.keys(output).length, 1); + assert.equal(output.default.entrypoints.length, 2); + assert.deepEqual( + output.default.entrypoints.map(e => e.importPath), + ['./app.js', './not-app.js'], + ); }); it('generates entrypoint for multiple bundles', async () => { @@ -334,17 +370,23 @@ describe('getEntrypointBundles()', () => { generatedBundles, }); - expect(Object.keys(output).length).to.equal(2); - expect(output.modern.options).to.equal(generatedBundles[0].options); - expect(output.legacy.options).to.equal(generatedBundles[1].options); - expect(output.modern.bundle).to.equal(generatedBundles[0].bundle); - expect(output.legacy.bundle).to.equal(generatedBundles[1].bundle); - expect(output.modern.entrypoints.length).to.equal(1); - expect(output.modern.entrypoints[0].chunk).to.equal(generatedBundles[0].bundle['app.js']); - expect(output.modern.entrypoints.map(e => e.importPath)).to.eql(['./app.js']); - expect(output.legacy.entrypoints.length).to.equal(1); - expect(output.legacy.entrypoints[0].chunk).to.equal(generatedBundles[1].bundle['app.js']); - expect(output.legacy.entrypoints.map(e => e.importPath)).to.eql(['./legacy/app.js']); + assert.equal(Object.keys(output).length, 2); + assert.equal(output.modern.options, generatedBundles[0].options); + assert.equal(output.legacy.options, generatedBundles[1].options); + assert.equal(output.modern.bundle, generatedBundles[0].bundle); + assert.equal(output.legacy.bundle, generatedBundles[1].bundle); + assert.equal(output.modern.entrypoints.length, 1); + assert.equal(output.modern.entrypoints[0].chunk, generatedBundles[0].bundle['app.js']); + assert.deepEqual( + output.modern.entrypoints.map(e => e.importPath), + ['./app.js'], + ); + assert.equal(output.legacy.entrypoints.length, 1); + assert.equal(output.legacy.entrypoints[0].chunk, generatedBundles[1].bundle['app.js']); + assert.deepEqual( + output.legacy.entrypoints.map(e => e.importPath), + ['./legacy/app.js'], + ); }); it('allows configuring a public path', async () => { @@ -353,8 +395,11 @@ describe('getEntrypointBundles()', () => { pluginOptions: { publicPath: '/static' }, }); - expect(Object.keys(output).length).to.equal(1); - expect(output.default.entrypoints.length).to.equal(1); - expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['/static/app.js']); + assert.equal(Object.keys(output).length, 1); + assert.equal(output.default.entrypoints.length, 1); + assert.deepEqual( + output.default.entrypoints.map(e => e.importPath), + ['/static/app.js'], + ); }); }); diff --git a/packages/rollup-plugin-html/test/src/output/getOutputHTML.test.ts b/packages/rollup-plugin-html/test/src/output/getOutputHTML.test.ts index 17ad92448c..3e860cf573 100644 --- a/packages/rollup-plugin-html/test/src/output/getOutputHTML.test.ts +++ b/packages/rollup-plugin-html/test/src/output/getOutputHTML.test.ts @@ -1,7 +1,9 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import path from 'path'; -import { getOutputHTML, GetOutputHTMLParams } from '../../../src/output/getOutputHTML.js'; -import { EntrypointBundle } from '../../../src/RollupPluginHTMLOptions.js'; +import { getOutputHTML } from '../../../dist/output/getOutputHTML.js'; +import type { GetOutputHTMLParams } from '../../../dist/output/getOutputHTML.js'; +import type { EntrypointBundle } from '../../../dist/RollupPluginHTMLOptions.js'; import { html } from '../../../../../test-utils/rollup-test-utils.js'; describe('getOutputHTML()', () => { @@ -34,16 +36,19 @@ describe('getOutputHTML()', () => { it('injects output into the input HTML', async () => { const output = await getOutputHTML(defaultOptions); - expect(html`${output}`).to.equal(html` - - - -

Input HTML

- - - - - `); + assert.equal( + html`${output}`, + html` + + + +

Input HTML

+ + + + + `, + ); }); it('generates a HTML file for multiple rollup bundles', async () => { @@ -63,22 +68,25 @@ describe('getOutputHTML()', () => { }; const output = await getOutputHTML({ ...defaultOptions, entrypointBundles }); - expect(html`${output}`).to.equal(html` - - - -

Input HTML

- - - - - - - `); + assert.equal( + html`${output}`, + html` + + + +

Input HTML

+ + + + + + + `, + ); }); it('can transform html output', async () => { @@ -90,16 +98,19 @@ describe('getOutputHTML()', () => { }, }); - expect(html`${output}`).to.equal(html` - - - -

Transformed Input HTML

- - - - - `); + assert.equal( + html`${output}`, + html` + + + +

Transformed Input HTML

+ + + + + `, + ); }); it('allows setting multiple html transform functions', async () => { @@ -114,16 +125,19 @@ describe('getOutputHTML()', () => { }, }); - expect(html`${output}`).to.equal(html` - - - -

Transformed Input HTML

- - - - - `); + assert.equal( + html`${output}`, + html` + + + +

Transformed Input HTML

+ + + + + `, + ); }); it('can combine external and regular transform functions', async () => { @@ -136,16 +150,19 @@ describe('getOutputHTML()', () => { externalTransformHtmlFns: [html => html.replace(/h1/g, 'h2')], }); - expect(html`${output}`).to.equal(html` - - - -

Transformed Input HTML

- - - - - `); + assert.equal( + html`${output}`, + html` + + + +

Transformed Input HTML

+ + + + + `, + ); }); it('can disable default injection', async () => { @@ -154,18 +171,21 @@ describe('getOutputHTML()', () => { defaultInjectDisabled: true, }); - expect(html`${output}`).to.equal(html` - - - -

Input HTML

- - - `); + assert.equal( + html`${output}`, + html` + + + +

Input HTML

+ + + `, + ); }); it('can converts absolute urls to full absolute urls', async () => { - const rootDir = path.resolve(__dirname, '..', '..', 'fixtures', 'assets'); + const rootDir = path.resolve(import.meta.dirname, '..', '..', 'fixtures', 'assets'); const hashed = new Map(); hashed.set(path.join(rootDir, 'image-social.png'), 'image-social-xxx.png'); @@ -195,23 +215,26 @@ describe('getOutputHTML()', () => { }, }); - expect(html`${output}`).to.equal(html` - - - - - - - - - - - `); + assert.equal( + html`${output}`, + html` + + + + + + + + + + + `, + ); }); it('can minify HTML', async () => { const htmlInput = ` - + @@ -239,7 +262,8 @@ describe('getOutputHTML()', () => { }, }); - expect(output).to.equal( + assert.equal( + output, '', ); }); diff --git a/packages/rollup-plugin-html/test/src/output/injectBundles.test.ts b/packages/rollup-plugin-html/test/src/output/injectBundles.test.ts index 6625159778..0cf2824f57 100644 --- a/packages/rollup-plugin-html/test/src/output/injectBundles.test.ts +++ b/packages/rollup-plugin-html/test/src/output/injectBundles.test.ts @@ -1,17 +1,18 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { getTextContent } from '@web/parse5-utils'; -import { expect } from 'chai'; import { parse, serialize } from 'parse5'; import { html } from '../../../../../test-utils/rollup-test-utils.js'; -import { injectBundles, createLoadScript } from '../../../src/output/injectBundles.js'; +import { injectBundles, createLoadScript } from '../../../dist/output/injectBundles.js'; describe('createLoadScript()', () => { it('creates a script for es modules', () => { // parse5 types are broken const scriptAst = createLoadScript('./app.js', 'es') as any; - expect(scriptAst.tagName).to.equal('script'); - expect(scriptAst.attrs).to.eql([ + assert.equal(scriptAst.tagName, 'script'); + assert.deepEqual(scriptAst.attrs, [ { name: 'type', value: 'module' }, { name: 'src', value: './app.js' }, ]); @@ -21,15 +22,15 @@ describe('createLoadScript()', () => { // parse5 types are broken const scriptAst = createLoadScript('./app.js', 'system') as any; - expect(scriptAst.tagName).to.equal('script'); - expect(getTextContent(scriptAst)).to.equal('System.import("./app.js");'); + assert.equal(scriptAst.tagName, 'script'); + assert.equal(getTextContent(scriptAst), 'System.import("./app.js");'); }); it('creates a script for other modules types', () => { const scriptAst = createLoadScript('./app.js', 'iife') as any; - expect(scriptAst.tagName).to.equal('script'); - expect(scriptAst.attrs).to.eql([ + assert.equal(scriptAst.tagName, 'script'); + assert.deepEqual(scriptAst.attrs, [ { name: 'src', value: './app.js' }, { name: 'defer', value: '' }, ]); @@ -62,15 +63,18 @@ describe('injectBundles()', () => { const htmlWithBundles = serialize(document); - expect(html`${htmlWithBundles}`).to.eql(html` - - - -

Hello world

- - - - `); + assert.deepEqual( + html`${htmlWithBundles}`, + html` + + + +

Hello world

+ + + + `, + ); }); it('can inject multiple bundles', () => { @@ -110,15 +114,18 @@ describe('injectBundles()', () => { const htmlWithBundles = serialize(document); - expect(html`${htmlWithBundles}`).to.eql(html` - - - -

Hello world

- - - - - `); + assert.deepEqual( + html`${htmlWithBundles}`, + html` + + + +

Hello world

+ + + + + `, + ); }); }); diff --git a/packages/rollup-plugin-html/test/src/output/injectedUpdatedAssetPaths.test.ts b/packages/rollup-plugin-html/test/src/output/injectedUpdatedAssetPaths.test.ts index 375527dde8..8b53f17f76 100644 --- a/packages/rollup-plugin-html/test/src/output/injectedUpdatedAssetPaths.test.ts +++ b/packages/rollup-plugin-html/test/src/output/injectedUpdatedAssetPaths.test.ts @@ -1,10 +1,11 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import path from 'path'; import { parse, serialize } from 'parse5'; import { html } from '../../../../../test-utils/rollup-test-utils.js'; -import { InputData } from '../../../src/input/InputData.js'; +import type { InputData } from '../../../dist/input/InputData.js'; -import { injectedUpdatedAssetPaths } from '../../../src/output/injectedUpdatedAssetPaths.js'; +import { injectedUpdatedAssetPaths } from '../../../dist/output/injectedUpdatedAssetPaths.js'; describe('injectedUpdatedAssetPaths()', () => { it('injects updated asset paths', () => { @@ -45,18 +46,21 @@ describe('injectedUpdatedAssetPaths()', () => { const result = serialize(document); - expect(html`${result}`).to.eql(html` - - - - - - - - - - - `); + assert.deepEqual( + html`${result}`, + html` + + + + + + + + + + + `, + ); }); it('handles a picture tag using source tags with srcset', () => { @@ -112,34 +116,37 @@ describe('injectedUpdatedAssetPaths()', () => { const result = serialize(document); - expect(html`${result}`).to.eql(html` - - - - - - - My Image Alternative Text - - - - `); + assert.deepEqual( + html`${result}`, + html` + + + + + + + My Image Alternative Text + + + + `, + ); }); it('handles video tag using source tags with src', () => { @@ -177,16 +184,19 @@ describe('injectedUpdatedAssetPaths()', () => { const result = serialize(document); - expect(html`${result}`).to.eql(html` - - - - - - - `); + assert.deepEqual( + html`${result}`, + html` + + + + + + + `, + ); }); it('handles virtual files', () => { @@ -224,17 +234,20 @@ describe('injectedUpdatedAssetPaths()', () => { const result = serialize(document); - expect(html`${result}`).to.eql(html` - - - - - - - - - - `); + assert.deepEqual( + html`${result}`, + html` + + + + + + + + + + `, + ); }); it('handles HTML files in a sub directory', () => { @@ -273,17 +286,20 @@ describe('injectedUpdatedAssetPaths()', () => { const result = serialize(document); - expect(html`${result}`).to.eql(html` - - - - - - - - - - `); + assert.deepEqual( + html`${result}`, + html` + + + + + + + + + + `, + ); }); it('handles virtual HTML files in a sub directory', () => { @@ -321,17 +337,20 @@ describe('injectedUpdatedAssetPaths()', () => { const result = serialize(document); - expect(html`${result}`).to.eql(html` - - - - - - - - - - `); + assert.deepEqual( + html`${result}`, + html` + + + + + + + + + + `, + ); }); it('prefixes a publicpath', () => { @@ -371,16 +390,19 @@ describe('injectedUpdatedAssetPaths()', () => { const result = serialize(document); - expect(html`${result}`).to.eql(html` - - - - - - - - - - `); + assert.deepEqual( + html`${result}`, + html` + + + + + + + + + + `, + ); }); }); diff --git a/packages/rollup-plugin-import-meta-assets/package.json b/packages/rollup-plugin-import-meta-assets/package.json index 8605c842bb..11141dd5cc 100644 --- a/packages/rollup-plugin-import-meta-assets/package.json +++ b/packages/rollup-plugin-import-meta-assets/package.json @@ -25,9 +25,9 @@ }, "scripts": { "test": "npm run test:node", - "test:node": "mocha test/**/*.test.js test/*.test.js --reporter dot", + "test:node": "node --test --test-force-exit test/**/*.test.js", "test:update-snapshots": "mocha test/**/*.test.js test/*.test.js --update-snapshots", - "test:watch": "npm run test:node -- --watch" + "test:watch": "node --test --test-force-exit --watch test/**/*.test.js" }, "files": [ "*.js", diff --git a/packages/rollup-plugin-import-meta-assets/test/integration.test.js b/packages/rollup-plugin-import-meta-assets/test/integration.test.js index f41023a1e2..1ee1724c56 100644 --- a/packages/rollup-plugin-import-meta-assets/test/integration.test.js +++ b/packages/rollup-plugin-import-meta-assets/test/integration.test.js @@ -1,7 +1,7 @@ const path = require('path'); const { rollup } = require('rollup'); -const { expect } = require('chai'); -const hanbi = require('hanbi'); +const assert = require('node:assert/strict'); +const { describe, it, beforeEach, afterEach, mock } = require('node:test'); const { importMetaAssets } = require('../src/rollup-plugin-import-meta-assets.js'); const { @@ -21,11 +21,11 @@ describe('rollup-plugin-import-meta-assets', () => { let consoleStub; beforeEach(() => { - consoleStub = hanbi.stubMethod(console, 'warn'); + consoleStub = mock.method(console, 'warn'); }); afterEach(() => { - hanbi.restore(); + mock.restoreAll(); cleanApp(); }); @@ -61,10 +61,12 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(5); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 5); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const justUrlObject = new URL( new URL('assets/one-BCCvKrTe.svg', import.meta.url).href ); @@ -87,10 +89,11 @@ describe('rollup-plugin-import-meta-assets', () => { searchParams, noExtension, }); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'assets/one-BCCvKrTe.svg', 'assets/two-C4stzVZW.svg', 'assets/three-DPeYetg3.svg', @@ -98,19 +101,23 @@ describe('rollup-plugin-import-meta-assets', () => { 'assets/five-DeBsXz7d', ]); - expect(assets['assets/one-BCCvKrTe.svg']).to.equal( + assert.equal( + assets['assets/one-BCCvKrTe.svg'], svg``, ); - expect(assets['assets/two-C4stzVZW.svg']).to.equal( + assert.equal( + assets['assets/two-C4stzVZW.svg'], svg``, ); - expect(assets['assets/three-DPeYetg3.svg']).to.equal( + assert.equal( + assets['assets/three-DPeYetg3.svg'], svg``, ); - expect(assets['assets/four-2QgOKKkO.svg']).to.equal( + assert.equal( + assets['assets/four-2QgOKKkO.svg'], svg``, ); - expect(assets['assets/five-DeBsXz7d']).to.equal('five'); + assert.equal(assets['assets/five-DeBsXz7d'], 'five'); }); it('simple bundle with transform assets', async () => { @@ -155,10 +162,12 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(5); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 5); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const justUrlObject = new URL( new URL('assets/one-QPKGlwhS.svg', import.meta.url).href ); @@ -181,10 +190,11 @@ describe('rollup-plugin-import-meta-assets', () => { searchParams, someJpg, }); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'assets/one-QPKGlwhS.svg', 'assets/two-T4ecKj7d.svg', 'assets/three-LuNZrcLX.svg', @@ -192,19 +202,23 @@ describe('rollup-plugin-import-meta-assets', () => { 'assets/image-B360jR14.jpg', ]); - expect(assets['assets/one-QPKGlwhS.svg']).to.equal( + assert.equal( + assets['assets/one-QPKGlwhS.svg'], svg`${svg``}`, ); - expect(assets['assets/two-T4ecKj7d.svg']).to.equal( + assert.equal( + assets['assets/two-T4ecKj7d.svg'], svg`${svg``}`, ); - expect(assets['assets/three-LuNZrcLX.svg']).to.equal( + assert.equal( + assets['assets/three-LuNZrcLX.svg'], svg`${svg``}`, ); - expect(assets['assets/four-Cf59sBI1.svg']).to.equal( + assert.equal( + assets['assets/four-Cf59sBI1.svg'], svg`${svg``}`, ); - expect(assets['assets/image-B360jR14.jpg']).to.equal('image.jpg'); + assert.equal(assets['assets/image-B360jR14.jpg'], 'image.jpg'); }); it('simple bundle with ignored assets', async () => { @@ -249,11 +263,13 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); // image.jpg is NOT transformed, so it keeps original URL - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const justUrlObject = new URL( new URL('assets/one-QPKGlwhS.svg', import.meta.url).href ); @@ -274,26 +290,31 @@ describe('rollup-plugin-import-meta-assets', () => { searchParams, someJpg, }); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'assets/one-QPKGlwhS.svg', 'assets/two-T4ecKj7d.svg', 'assets/three-LuNZrcLX.svg', 'assets/four-Cf59sBI1.svg', ]); - expect(assets['assets/one-QPKGlwhS.svg']).to.equal( + assert.equal( + assets['assets/one-QPKGlwhS.svg'], svg`${svg``}`, ); - expect(assets['assets/two-T4ecKj7d.svg']).to.equal( + assert.equal( + assets['assets/two-T4ecKj7d.svg'], svg`${svg``}`, ); - expect(assets['assets/three-LuNZrcLX.svg']).to.equal( + assert.equal( + assets['assets/three-LuNZrcLX.svg'], svg`${svg``}`, ); - expect(assets['assets/four-Cf59sBI1.svg']).to.equal( + assert.equal( + assets['assets/four-Cf59sBI1.svg'], svg`${svg``}`, ); }); @@ -343,10 +364,12 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const nameOne = 'one-name'; const imageOne = new URL( new URL('assets/one-BCCvKrTe.svg', import.meta.url).href @@ -373,26 +396,31 @@ describe('rollup-plugin-import-meta-assets', () => { [nameThree]: imageThree, [nameFour]: imageFour, }); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'assets/one-BCCvKrTe.svg', 'assets/two-C4stzVZW.svg', 'assets/three-DPeYetg3.svg', 'assets/four-2QgOKKkO.svg', ]); - expect(assets['assets/one-BCCvKrTe.svg']).to.equal( + assert.equal( + assets['assets/one-BCCvKrTe.svg'], svg``, ); - expect(assets['assets/two-C4stzVZW.svg']).to.equal( + assert.equal( + assets['assets/two-C4stzVZW.svg'], svg``, ); - expect(assets['assets/three-DPeYetg3.svg']).to.equal( + assert.equal( + assets['assets/three-DPeYetg3.svg'], svg``, ); - expect(assets['assets/four-2QgOKKkO.svg']).to.equal( + assert.equal( + assets['assets/four-2QgOKKkO.svg'], svg``, ); }); @@ -444,10 +472,12 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const nameOne = 'one-name'; const imageOne = new URL( new URL('assets/one-BCCvKrTe.svg', import.meta.url).href @@ -474,26 +504,31 @@ describe('rollup-plugin-import-meta-assets', () => { [nameThree]: imageThree, [nameFour]: imageFour, }); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'assets/one-BCCvKrTe.svg', 'assets/two-C4stzVZW.svg', 'assets/three-DPeYetg3.svg', 'assets/four-2QgOKKkO.svg', ]); - expect(assets['assets/one-BCCvKrTe.svg']).to.equal( + assert.equal( + assets['assets/one-BCCvKrTe.svg'], svg``, ); - expect(assets['assets/two-C4stzVZW.svg']).to.equal( + assert.equal( + assets['assets/two-C4stzVZW.svg'], svg``, ); - expect(assets['assets/three-DPeYetg3.svg']).to.equal( + assert.equal( + assets['assets/three-DPeYetg3.svg'], svg``, ); - expect(assets['assets/four-2QgOKKkO.svg']).to.equal( + assert.equal( + assets['assets/four-2QgOKKkO.svg'], svg``, ); }); @@ -536,10 +571,12 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const nameOne = 'one-name'; const imageOne = new URL( new URL('assets/one-deep-BCCvKrTe.svg', import.meta.url).href @@ -566,26 +603,31 @@ describe('rollup-plugin-import-meta-assets', () => { [nameThree]: imageThree, [nameFour]: imageFour, }); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'assets/one-deep-BCCvKrTe.svg', 'assets/two-deep-C4stzVZW.svg', 'assets/three-deep-DPeYetg3.svg', 'assets/four-deep-2QgOKKkO.svg', ]); - expect(assets['assets/one-deep-BCCvKrTe.svg']).to.equal( + assert.equal( + assets['assets/one-deep-BCCvKrTe.svg'], svg``, ); - expect(assets['assets/two-deep-C4stzVZW.svg']).to.equal( + assert.equal( + assets['assets/two-deep-C4stzVZW.svg'], svg``, ); - expect(assets['assets/three-deep-DPeYetg3.svg']).to.equal( + assert.equal( + assets['assets/three-deep-DPeYetg3.svg'], svg``, ); - expect(assets['assets/four-deep-2QgOKKkO.svg']).to.equal( + assert.equal( + assets['assets/four-deep-2QgOKKkO.svg'], svg``, ); }); @@ -632,10 +674,12 @@ describe('rollup-plugin-import-meta-assets', () => { path.relative(rootDir, asset.originalFileNames[0]).split(path.sep).join('/'), }); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const nameOne = 'one-name'; const imageOne = new URL( new URL('one/one-deep.svg', import.meta.url).href @@ -665,26 +709,31 @@ describe('rollup-plugin-import-meta-assets', () => { [nameThree]: imageThree, [nameFour]: imageFour, }); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'one/one-deep.svg', 'one/two/two-deep.svg', 'one/two/three/three-deep.svg', 'one/two/three/four/four-deep.svg', ]); - expect(assets['one/one-deep.svg']).to.equal( + assert.equal( + assets['one/one-deep.svg'], svg``, ); - expect(assets['one/two/two-deep.svg']).to.equal( + assert.equal( + assets['one/two/two-deep.svg'], svg``, ); - expect(assets['one/two/three/three-deep.svg']).to.equal( + assert.equal( + assets['one/two/three/three-deep.svg'], svg``, ); - expect(assets['one/two/three/four/four-deep.svg']).to.equal( + assert.equal( + assets['one/two/three/four/four-deep.svg'], svg``, ); }); @@ -734,45 +783,59 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(4); - expect(Object.keys(assets)).to.have.lengthOf(2); + assert.equal(Object.keys(chunks).length, 4); + assert.equal(Object.keys(assets).length, 2); // one and two keep original URLs (excluded) - expect(chunks['one.js']).to.equal(js` + assert.equal( + chunks['one.js'], + js` const nameOne = 'one-name'; const imageOne = new URL('../one.svg', import.meta.url).href; export { imageOne, nameOne }; - `); - expect(chunks['two.js']).to.equal(js` + `, + ); + assert.equal( + chunks['two.js'], + js` const nameTwo = 'two-name'; const imageTwo = new URL('../../two.svg', import.meta.url).href; export { imageTwo, nameTwo }; - `); + `, + ); // three and four have transformed URLs (included) - expect(chunks['three.js']).to.equal(js` + assert.equal( + chunks['three.js'], + js` const nameThree = 'three-name'; const imageThree = new URL( new URL('assets/three-DPeYetg3.svg', import.meta.url).href ).href; export { imageThree, nameThree }; - `); - expect(chunks['four.js']).to.equal(js` + `, + ); + assert.equal( + chunks['four.js'], + js` const nameFour = 'four-name'; const imageFour = new URL( new URL('assets/four-2QgOKKkO.svg', import.meta.url).href ).href; export { imageFour, nameFour }; - `); + `, + ); - expect(assets['assets/three-DPeYetg3.svg']).to.equal( + assert.equal( + assets['assets/three-DPeYetg3.svg'], svg``, ); - expect(assets['assets/four-2QgOKKkO.svg']).to.equal( + assert.equal( + assets['assets/four-2QgOKKkO.svg'], svg``, ); @@ -781,10 +844,10 @@ describe('rollup-plugin-import-meta-assets', () => { const threeChunk = output.find(({ fileName }) => fileName === 'three.js'); const fourChunk = output.find(({ fileName }) => fileName === 'four.js'); - expect(oneChunk.referencedFiles).to.deep.equal([]); - expect(twoChunk.referencedFiles).to.deep.equal([]); - expect(threeChunk.referencedFiles).to.deep.equal(['assets/three-DPeYetg3.svg']); - expect(fourChunk.referencedFiles).to.deep.equal(['assets/four-2QgOKKkO.svg']); + assert.deepEqual(oneChunk.referencedFiles, []); + assert.deepEqual(twoChunk.referencedFiles, []); + assert.deepEqual(threeChunk.referencedFiles, ['assets/three-DPeYetg3.svg']); + assert.deepEqual(fourChunk.referencedFiles, ['assets/four-2QgOKKkO.svg']); }); it('bad URL example', async () => { @@ -810,7 +873,7 @@ describe('rollup-plugin-import-meta-assets', () => { error = e; } - expect(error.message).to.match(/no such file or directory/); + assert.ok(error.message.match(/no such file or directory/)); }); it('bad URL example with warnOnError: true', async () => { @@ -830,12 +893,16 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); await build.generate(outputConfig); - expect(consoleStub.callCount).to.equal(2); - expect(consoleStub.getCall(0).args[0]).to.match( - /ENOENT: no such file or directory, open '.*[/\\]absolute-path\.svg'/, + assert.equal(consoleStub.mock.callCount(), 2); + assert.ok( + consoleStub.mock.calls[0].arguments[0].match( + /ENOENT: no such file or directory, open '.*[/\\]absolute-path\.svg'/, + ), ); - expect(consoleStub.getCall(1).args[0]).to.match( - /ENOENT: no such file or directory, open '.*[/\\]missing-relative-path\.svg'/, + assert.ok( + consoleStub.mock.calls[1].arguments[0].match( + /ENOENT: no such file or directory, open '.*[/\\]missing-relative-path\.svg'/, + ), ); }); @@ -854,21 +921,25 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(1); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 1); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const backticksImg = new URL( new URL('assets/one-deep-BCCvKrTe.svg', import.meta.url).href ); console.log(backticksImg); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal(['assets/one-deep-BCCvKrTe.svg']); + assert.deepEqual(appChunk.referencedFiles, ['assets/one-deep-BCCvKrTe.svg']); - expect(assets['assets/one-deep-BCCvKrTe.svg']).to.equal( + assert.equal( + assets['assets/one-deep-BCCvKrTe.svg'], svg``, ); }); @@ -898,10 +969,12 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(3); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 3); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` function __variableDynamicURLRuntime0__(path) { switch (path) { case './assets/images/image-one.svg': @@ -930,22 +1003,26 @@ describe('rollup-plugin-import-meta-assets', () => { const paths = images.map((name) => __variableDynamicURLRuntime0__(\`./assets/images/image-\${name}.svg\`)); console.log(paths); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'assets/image-two-C4stzVZW.svg', 'assets/image-three-DPeYetg3.svg', 'assets/image-one-BCCvKrTe.svg', ]); - expect(assets['assets/image-one-BCCvKrTe.svg']).to.equal( + assert.equal( + assets['assets/image-one-BCCvKrTe.svg'], svg``, ); - expect(assets['assets/image-two-C4stzVZW.svg']).to.equal( + assert.equal( + assets['assets/image-two-C4stzVZW.svg'], svg``, ); - expect(assets['assets/image-three-DPeYetg3.svg']).to.equal( + assert.equal( + assets['assets/image-three-DPeYetg3.svg'], svg``, ); }); @@ -992,10 +1069,12 @@ describe('rollup-plugin-import-meta-assets', () => { const build = await rollup(config); const { output, chunks, assets } = await generateTestBundle(build, outputConfig); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const justUrlObject = new URL( new URL('assets/one-BCCvKrTe.svg', import.meta.url).href ); @@ -1023,26 +1102,31 @@ describe('rollup-plugin-import-meta-assets', () => { searchParams, directories, }); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'assets/one-BCCvKrTe.svg', 'assets/two-C4stzVZW.svg', 'assets/three-DPeYetg3.svg', 'assets/four-2QgOKKkO.svg', ]); - expect(assets['assets/one-BCCvKrTe.svg']).to.equal( + assert.equal( + assets['assets/one-BCCvKrTe.svg'], svg``, ); - expect(assets['assets/two-C4stzVZW.svg']).to.equal( + assert.equal( + assets['assets/two-C4stzVZW.svg'], svg``, ); - expect(assets['assets/three-DPeYetg3.svg']).to.equal( + assert.equal( + assets['assets/three-DPeYetg3.svg'], svg``, ); - expect(assets['assets/four-2QgOKKkO.svg']).to.equal( + assert.equal( + assets['assets/four-2QgOKKkO.svg'], svg``, ); }); @@ -1077,10 +1161,12 @@ describe('rollup-plugin-import-meta-assets', () => { path.relative(rootDir, asset.originalFileNames[0]).split(path.sep).join('/'), }); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(3); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 3); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const images = ['one', 'two']; const paths = images.map((name) => @@ -1088,18 +1174,22 @@ describe('rollup-plugin-import-meta-assets', () => { ); console.log(paths); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal(['assets/images/image-one.svg']); + assert.deepEqual(appChunk.referencedFiles, ['assets/images/image-one.svg']); - expect(assets['assets/images/image-one.svg']).to.equal( + assert.equal( + assets['assets/images/image-one.svg'], svg``, ); - expect(assets['assets/images/image-two.svg']).to.equal( + assert.equal( + assets['assets/images/image-two.svg'], svg``, ); - expect(assets['assets/images/image-three.svg']).to.equal( + assert.equal( + assets['assets/images/image-three.svg'], svg``, ); }); @@ -1138,10 +1228,12 @@ describe('rollup-plugin-import-meta-assets', () => { path.relative(rootDir, asset.originalFileNames[0]).split(path.sep).join('/'), }); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const images = { 'category-name': ['image-name'], }; @@ -1153,21 +1245,26 @@ describe('rollup-plugin-import-meta-assets', () => { ); console.log(paths); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal(['assets/images/category-one/image-one.svg']); + assert.deepEqual(appChunk.referencedFiles, ['assets/images/category-one/image-one.svg']); - expect(assets['assets/images/category-one/image-one.svg']).to.equal( + assert.equal( + assets['assets/images/category-one/image-one.svg'], svg``, ); - expect(assets['assets/images/category-one/image-two.svg']).to.equal( + assert.equal( + assets['assets/images/category-one/image-two.svg'], svg``, ); - expect(assets['assets/images/category-two/image-three.svg']).to.equal( + assert.equal( + assets['assets/images/category-two/image-three.svg'], svg``, ); - expect(assets['assets/images/category-two/image-four.svg']).to.equal( + assert.equal( + assets['assets/images/category-two/image-four.svg'], svg``, ); }); @@ -1206,10 +1303,12 @@ describe('rollup-plugin-import-meta-assets', () => { path.relative(rootDir, asset.originalFileNames[0]).split(path.sep).join('/'), }); - expect(Object.keys(chunks)).to.have.lengthOf(1); - expect(Object.keys(assets)).to.have.lengthOf(4); + assert.equal(Object.keys(chunks).length, 1); + assert.equal(Object.keys(assets).length, 4); - expect(chunks['app.js']).to.equal(js` + assert.equal( + chunks['app.js'], + js` const images = { 'category-name': ['image-name'], }; @@ -1221,23 +1320,28 @@ describe('rollup-plugin-import-meta-assets', () => { ); console.log(paths); - `); + `, + ); const appChunk = output.find(({ fileName }) => fileName === 'app.js'); - expect(appChunk.referencedFiles).to.deep.equal([ + assert.deepEqual(appChunk.referencedFiles, [ 'assets/images/category-one/static/image-one.svg', ]); - expect(assets['assets/images/category-one/static/image-one.svg']).to.equal( + assert.equal( + assets['assets/images/category-one/static/image-one.svg'], svg``, ); - expect(assets['assets/images/category-one/static/image-two.svg']).to.equal( + assert.equal( + assets['assets/images/category-one/static/image-two.svg'], svg``, ); - expect(assets['assets/images/category-two/static/image-three.svg']).to.equal( + assert.equal( + assets['assets/images/category-two/static/image-three.svg'], svg``, ); - expect(assets['assets/images/category-two/static/image-four.svg']).to.equal( + assert.equal( + assets['assets/images/category-two/static/image-four.svg'], svg``, ); }); diff --git a/packages/rollup-plugin-polyfills-loader/package.json b/packages/rollup-plugin-polyfills-loader/package.json index 003a175d18..15b7cbef6e 100644 --- a/packages/rollup-plugin-polyfills-loader/package.json +++ b/packages/rollup-plugin-polyfills-loader/package.json @@ -25,9 +25,9 @@ "node": ">=22.0.0" }, "scripts": { - "test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", + "test:node": "node --test --test-force-exit test/**/*.test.ts", "test:update-snapshots": "mocha test/**/*.test.ts --require ts-node/register --update-snapshots", - "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test" + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/rollup-plugin-polyfills-loader/test/src/createPolyfillsLoaderConfig.test.ts b/packages/rollup-plugin-polyfills-loader/test/src/createPolyfillsLoaderConfig.test.ts index 3e15905d13..c3bf6e8b3c 100644 --- a/packages/rollup-plugin-polyfills-loader/test/src/createPolyfillsLoaderConfig.test.ts +++ b/packages/rollup-plugin-polyfills-loader/test/src/createPolyfillsLoaderConfig.test.ts @@ -1,5 +1,6 @@ -import { expect } from 'chai'; -import { createPolyfillsLoaderConfig } from '../../src/createPolyfillsLoaderConfig.js'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { createPolyfillsLoaderConfig } from '../../dist/createPolyfillsLoaderConfig.js'; describe('createPolyfillsLoaderConfig()', () => { it('creates a config for a single module build', () => { @@ -12,7 +13,7 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const config = createPolyfillsLoaderConfig(pluginConfig, bundle); - expect(config).to.eql({ + assert.deepEqual(config, { legacy: undefined, modern: { files: [{ path: 'app.js', type: 'module', attributes: [] }] }, polyfills: undefined, @@ -33,7 +34,7 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const config = createPolyfillsLoaderConfig(pluginConfig, bundle); - expect(config).to.eql({ + assert.deepEqual(config, { legacy: undefined, modern: { files: [ @@ -59,7 +60,7 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const config = createPolyfillsLoaderConfig(pluginConfig, bundle); - expect(config).to.eql({ + assert.deepEqual(config, { legacy: undefined, modern: { files: [{ path: 'app.js', type: 'systemjs', attributes: [] }] }, polyfills: undefined, @@ -86,7 +87,7 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const config = createPolyfillsLoaderConfig(pluginConfig, undefined, bundles); - expect(config).to.eql({ + assert.deepEqual(config, { modern: { files: [{ path: 'app.js', type: 'module', attributes: [] }] }, legacy: [ { @@ -125,7 +126,7 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const config = createPolyfillsLoaderConfig(pluginConfig, undefined, bundles); - expect(config).to.eql({ + assert.deepEqual(config, { modern: { files: [{ path: 'app.js', type: 'module', attributes: [] }] }, legacy: [ { @@ -165,7 +166,7 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const config = createPolyfillsLoaderConfig(pluginConfig, undefined, bundles); - expect(config).to.eql({ + assert.deepEqual(config, { modern: { files: [{ path: 'app.js', type: 'script', attributes: [] }] }, legacy: [ { @@ -190,7 +191,7 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const config = createPolyfillsLoaderConfig(pluginConfig, bundle); - expect(config).to.eql({ + assert.deepEqual(config, { legacy: undefined, modern: { files: [{ path: 'app.js', type: 'module', attributes: [] }] }, polyfills: { fetch: true, webcomponents: true }, @@ -210,7 +211,7 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const action = () => createPolyfillsLoaderConfig(pluginConfig, bundle); - expect(action).to.throw(); + assert.throws(action); }); it('throws when a multiple builds are output while no builds are configured', () => { @@ -228,7 +229,7 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const action = () => createPolyfillsLoaderConfig(pluginConfig, undefined, bundles); - expect(action).to.throw(); + assert.throws(action); }); it('throws when the modern build could not be found', () => { @@ -249,6 +250,6 @@ describe('createPolyfillsLoaderConfig()', () => { // @ts-ignore const action = () => createPolyfillsLoaderConfig(pluginConfig, undefined, bundles); - expect(action).to.throw(); + assert.throws(action); }); }); diff --git a/packages/rollup-plugin-polyfills-loader/test/src/rollupPluginPolyfillsLoader.test.ts b/packages/rollup-plugin-polyfills-loader/test/src/rollupPluginPolyfillsLoader.test.ts index 65e86d6b35..5b220ec427 100644 --- a/packages/rollup-plugin-polyfills-loader/test/src/rollupPluginPolyfillsLoader.test.ts +++ b/packages/rollup-plugin-polyfills-loader/test/src/rollupPluginPolyfillsLoader.test.ts @@ -1,14 +1,16 @@ /* eslint-disable no-await-in-loop */ -import { OutputChunk, rollup, OutputAsset, RollupOptions, OutputOptions } from 'rollup'; -import { expect } from 'chai'; +import { rollup } from 'rollup'; +import type { OutputChunk, OutputAsset, RollupOptions, OutputOptions } from 'rollup'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import fs from 'fs'; import path from 'path'; import { rollupPluginHTML as html } from '@web/rollup-plugin-html'; -import polyfillsLoader from '../../src/index.js'; +import { polyfillsLoader } from '../../dist/index.js'; type Output = (OutputChunk | OutputAsset)[]; -const relativeUrl = `./${path.relative(process.cwd(), path.join(__dirname, '..'))}`; +const relativeUrl = `./${path.relative(process.cwd(), path.join(import.meta.dirname, '..'))}`; const updateSnapshots = process.argv.includes('--update-snapshots'); @@ -26,7 +28,7 @@ interface SnapshotArgs { } async function testSnapshot({ name, fileName, inputOptions, outputOptions }: SnapshotArgs) { - const snapshotPath = path.join(__dirname, '..', 'snapshots', `${name}.html`); + const snapshotPath = path.join(import.meta.dirname, '..', 'snapshots', `${name}.html`); const bundle = await rollup(inputOptions); let output; for (const outputConfig of outputOptions) { @@ -42,8 +44,8 @@ async function testSnapshot({ name, fileName, inputOptions, outputOptions }: Sna fs.writeFileSync(snapshotPath, file.source, 'utf-8'); } else { const snapshot = fs.readFileSync(snapshotPath, 'utf-8'); - expect(file.source.trim()).to.equal(snapshot.trim()); - // expect(file.source.replace(/\s/g, '')).to.equal(snapshot.replace(/\s/g, '')); + assert.equal(file.source.trim(), snapshot.trim()); + // assert.equal(file.source.replace(/\s/g, ''), snapshot.replace(/\s/g, '')); } return output; } @@ -55,10 +57,8 @@ const defaultOutputOptions: OutputOptions[] = [ }, ]; -describe('rollup-plugin-polyfills-loader', function describe() { - // bootup of the first test can take a long time in CI to load all the polyfills - this.timeout(5000); - +// bootup of the first test can take a long time in CI to load all the polyfills +describe('rollup-plugin-polyfills-loader', { timeout: 5000 }, () => { it('can inject a polyfills loader with a single output', async () => { const inputOptions: RollupOptions = { plugins: [ @@ -225,8 +225,8 @@ describe('rollup-plugin-polyfills-loader', function describe() { outputOptions: defaultOutputOptions, }); - expect(output.find(o => o.fileName.startsWith('polyfills/webcomponents'))).to.exist; - expect(output.find(o => o.fileName.startsWith('polyfills/fetch'))).to.exist; + assert.ok(output.find(o => o.fileName.startsWith('polyfills/webcomponents'))); + assert.ok(output.find(o => o.fileName.startsWith('polyfills/fetch'))); }); it('can inject with multiple build outputs', async () => { diff --git a/packages/rollup-plugin-polyfills-loader/test/src/utils.test.ts b/packages/rollup-plugin-polyfills-loader/test/src/utils.test.ts index 22ca42691a..64fd5fecff 100644 --- a/packages/rollup-plugin-polyfills-loader/test/src/utils.test.ts +++ b/packages/rollup-plugin-polyfills-loader/test/src/utils.test.ts @@ -1,53 +1,59 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { fileTypes } from '@web/polyfills-loader'; -import { shouldInjectLoader } from '../../src/utils.js'; +import { shouldInjectLoader } from '../../dist/utils.js'; describe('shouldInjectLoader', () => { it('returns true when modern contains non-module or script', () => { - expect( + assert.equal( shouldInjectLoader({ modern: { files: [{ type: fileTypes.SYSTEMJS, path: '' }] }, }), - ).to.equal(true); + true, + ); }); it('returns true when there are legacy files', () => { - expect( + assert.equal( shouldInjectLoader({ modern: { files: [{ type: fileTypes.MODULE, path: '' }] }, legacy: [{ test: '', files: [{ type: fileTypes.SYSTEMJS, path: '' }] }], }), - ).to.equal(true); + true, + ); }); it('returns true when there are polyfills', () => { - expect( + assert.equal( shouldInjectLoader({ modern: { files: [{ type: fileTypes.MODULE, path: '' }] }, polyfills: { fetch: true, }, }), - ).to.equal(true); + true, + ); - expect( + assert.equal( shouldInjectLoader({ modern: { files: [{ type: fileTypes.MODULE, path: '' }] }, polyfills: { regeneratorRuntime: 'always', }, }), - ).to.equal(true); + true, + ); }); it('returns true when there are custom polyfills', () => { - expect( + assert.equal( shouldInjectLoader({ modern: { files: [{ type: fileTypes.MODULE, path: '' }] }, polyfills: { custom: [{ test: '', path: '', name: '' }], }, }), - ).to.equal(true); + true, + ); }); }); diff --git a/packages/test-runner-chrome/package.json b/packages/test-runner-chrome/package.json index 4dc77f206b..928a02aa34 100644 --- a/packages/test-runner-chrome/package.json +++ b/packages/test-runner-chrome/package.json @@ -25,9 +25,7 @@ "node": ">=22.0.0" }, "scripts": { - "build": "tsc", - "test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", - "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test" + "build": "tsc" }, "files": [ "*.d.ts", diff --git a/packages/test-runner-commands/package.json b/packages/test-runner-commands/package.json index a0ea656d47..6e074d6548 100644 --- a/packages/test-runner-commands/package.json +++ b/packages/test-runner-commands/package.json @@ -30,8 +30,8 @@ }, "scripts": { "build": "tsc", - "test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", - "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test --watch-ignore **/*.snap.js" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", @@ -55,7 +55,6 @@ "devDependencies": { "@web/test-runner-chrome": "^0.18.0", "@web/test-runner-playwright": "^0.11.0", - "@web/test-runner-webdriver": "^0.9.0", - "mocha": "^10.8.2" + "@web/test-runner-webdriver": "^0.9.0" } } diff --git a/packages/test-runner-commands/test/a11y-snapshot/a11ySnapshotPlugin.test.ts b/packages/test-runner-commands/test/a11y-snapshot/a11ySnapshotPlugin.test.ts index bc57f48537..f54e8a23e3 100644 --- a/packages/test-runner-commands/test/a11y-snapshot/a11ySnapshotPlugin.test.ts +++ b/packages/test-runner-commands/test/a11y-snapshot/a11ySnapshotPlugin.test.ts @@ -1,16 +1,15 @@ +import { describe, it } from 'node:test'; import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; import { playwrightLauncher } from '@web/test-runner-playwright'; -import { a11ySnapshotPlugin } from '../../src/a11ySnapshotPlugin.js'; +import { a11ySnapshotPlugin } from '../../dist/a11ySnapshotPlugin.js'; describe('a11ySnapshotPlugin', function test() { - this.timeout(20000); - it('can find accessibility nodes in the returned accessibility tree on puppeteer', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [chromeLauncher()], plugins: [a11ySnapshotPlugin()], }); @@ -18,7 +17,7 @@ describe('a11ySnapshotPlugin', function test() { it('can find accessibility nodes in the returned accessibility tree on playwright', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [ playwrightLauncher({ product: 'chromium' }), playwrightLauncher({ product: 'firefox' }), diff --git a/packages/test-runner-commands/test/emulate-media/emulateMediaPlugin.test.ts b/packages/test-runner-commands/test/emulate-media/emulateMediaPlugin.test.ts index 276b150650..ed52d49293 100644 --- a/packages/test-runner-commands/test/emulate-media/emulateMediaPlugin.test.ts +++ b/packages/test-runner-commands/test/emulate-media/emulateMediaPlugin.test.ts @@ -1,18 +1,17 @@ +import { describe, it } from 'node:test'; import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; import { playwrightLauncher } from '@web/test-runner-playwright'; -import { emulateMediaPlugin } from '../../src/emulateMediaPlugin.js'; +import { emulateMediaPlugin } from '../../dist/emulateMediaPlugin.js'; describe('emulateMediaPlugin', function test() { - this.timeout(20000); - it('can emulate media on puppeteer', async () => { await runTests({ files: [ - path.join(__dirname, 'browser-test.js'), - path.join(__dirname, 'prefers-reduced-motion-test.js'), + path.join(import.meta.dirname, 'browser-test.js'), + path.join(import.meta.dirname, 'prefers-reduced-motion-test.js'), ], browsers: [chromeLauncher()], @@ -23,8 +22,8 @@ describe('emulateMediaPlugin', function test() { it('can emulate media on playwright', async () => { await runTests({ files: [ - path.join(__dirname, 'browser-test.js'), - path.join(__dirname, 'prefers-reduced-motion-test.js'), + path.join(import.meta.dirname, 'browser-test.js'), + path.join(import.meta.dirname, 'prefers-reduced-motion-test.js'), ], browsers: [ playwrightLauncher({ product: 'chromium' }), @@ -37,7 +36,7 @@ describe('emulateMediaPlugin', function test() { it('can emulate forced-colors on playwright, except webkit', async () => { await runTests({ - files: [path.join(__dirname, 'forced-colors-test.js')], + files: [path.join(import.meta.dirname, 'forced-colors-test.js')], browsers: [ playwrightLauncher({ product: 'chromium' }), playwrightLauncher({ product: 'firefox' }), diff --git a/packages/test-runner-commands/test/execute-server-command/executeServerCommand.test.ts b/packages/test-runner-commands/test/execute-server-command/executeServerCommand.test.ts index aa6019acea..cbf7d7cc5f 100644 --- a/packages/test-runner-commands/test/execute-server-command/executeServerCommand.test.ts +++ b/packages/test-runner-commands/test/execute-server-command/executeServerCommand.test.ts @@ -1,11 +1,10 @@ +import { describe, it } from 'node:test'; import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; import type { Logger } from '@web/dev-server-core'; describe('executeServerCommand', function test() { - this.timeout(20000); - it('can execute commands', async () => { const logger: Logger = { ...console, @@ -26,7 +25,7 @@ describe('executeServerCommand', function test() { }; await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], logger, browsers: [chromeLauncher()], plugins: [ diff --git a/packages/test-runner-commands/test/file/filePlugin.test.ts b/packages/test-runner-commands/test/file/filePlugin.test.ts index b53fc9007e..07f587cb62 100644 --- a/packages/test-runner-commands/test/file/filePlugin.test.ts +++ b/packages/test-runner-commands/test/file/filePlugin.test.ts @@ -1,15 +1,14 @@ +import { describe, it } from 'node:test'; import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; -import { filePlugin } from '../../src/filePlugin.js'; +import { filePlugin } from '../../dist/filePlugin.js'; describe('filePlugin', function test() { - this.timeout(20000); - it('passes file plugin tests', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [chromeLauncher()], plugins: [filePlugin()], logger: { diff --git a/packages/test-runner-commands/test/select-option/selectOptionPlugin.test.ts b/packages/test-runner-commands/test/select-option/selectOptionPlugin.test.ts index dc22342bde..b7c221ce8a 100644 --- a/packages/test-runner-commands/test/select-option/selectOptionPlugin.test.ts +++ b/packages/test-runner-commands/test/select-option/selectOptionPlugin.test.ts @@ -1,16 +1,15 @@ +import { describe, it } from 'node:test'; import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; import { playwrightLauncher } from '@web/test-runner-playwright'; -import { selectOptionPlugin } from '../../src/selectOptionPlugin.js'; +import { selectOptionPlugin } from '../../dist/selectOptionPlugin.js'; describe('selectOptionPlugin', function test() { - this.timeout(20000); - it('can send keys on puppeteer', async () => { await runTests({ - files: [path.join(__dirname, 'puppeteer-test.js')], + files: [path.join(import.meta.dirname, 'puppeteer-test.js')], browsers: [chromeLauncher()], plugins: [selectOptionPlugin()], }); @@ -18,7 +17,7 @@ describe('selectOptionPlugin', function test() { it('can send keys on playwright', async () => { await runTests({ - files: [path.join(__dirname, 'playwright-test.js')], + files: [path.join(import.meta.dirname, 'playwright-test.js')], browsers: [ playwrightLauncher({ product: 'chromium' }), playwrightLauncher({ product: 'firefox' }), diff --git a/packages/test-runner-commands/test/send-keys/sendKeysPlugin.test.ts b/packages/test-runner-commands/test/send-keys/sendKeysPlugin.test.ts index 3d823f37bd..2502e40a11 100644 --- a/packages/test-runner-commands/test/send-keys/sendKeysPlugin.test.ts +++ b/packages/test-runner-commands/test/send-keys/sendKeysPlugin.test.ts @@ -1,16 +1,15 @@ +import { describe, it } from 'node:test'; import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; import { playwrightLauncher } from '@web/test-runner-playwright'; -import { sendKeysPlugin } from '../../src/sendKeysPlugin.js'; +import { sendKeysPlugin } from '../../dist/sendKeysPlugin.js'; describe('sendKeysPlugin', function test() { - this.timeout(20000); - it('can send keys on puppeteer', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [chromeLauncher()], plugins: [sendKeysPlugin()], }); @@ -18,7 +17,7 @@ describe('sendKeysPlugin', function test() { it('can send keys on playwright', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [ playwrightLauncher({ product: 'chromium' }), playwrightLauncher({ product: 'firefox' }), diff --git a/packages/test-runner-commands/test/send-mouse/sendMousePlugin.test.ts b/packages/test-runner-commands/test/send-mouse/sendMousePlugin.test.ts index a3d2b81305..582913f17e 100644 --- a/packages/test-runner-commands/test/send-mouse/sendMousePlugin.test.ts +++ b/packages/test-runner-commands/test/send-mouse/sendMousePlugin.test.ts @@ -1,18 +1,17 @@ +import { after, before, describe, it } from 'node:test'; import path from 'path'; import selenium from 'selenium-standalone'; import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; import { webdriverLauncher } from '@web/test-runner-webdriver'; import { playwrightLauncher } from '@web/test-runner-playwright'; -import { sendMousePlugin } from '../../src/sendMousePlugin.js'; -import { startSeleniumServer } from '../selenium-server.js'; +import { sendMousePlugin } from '../../dist/sendMousePlugin.js'; +import { startSeleniumServer } from '../selenium-server.ts'; describe('sendMousePlugin', function test() { - this.timeout(50000); - it('can send mouse on puppeteer', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [chromeLauncher()], plugins: [sendMousePlugin()], }); @@ -20,7 +19,7 @@ describe('sendMousePlugin', function test() { it('can send mouse on playwright', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [ playwrightLauncher({ product: 'chromium' }), playwrightLauncher({ product: 'firefox' }), @@ -52,7 +51,7 @@ describe('sendMousePlugin', function test() { it('can send mouse on webdriver', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], concurrency: 1, browsers: [ webdriverLauncher({ diff --git a/packages/test-runner-commands/test/set-user-agent/setUserAgentPlugin.test.ts b/packages/test-runner-commands/test/set-user-agent/setUserAgentPlugin.test.ts index 47af2f2c94..933e7ddb30 100644 --- a/packages/test-runner-commands/test/set-user-agent/setUserAgentPlugin.test.ts +++ b/packages/test-runner-commands/test/set-user-agent/setUserAgentPlugin.test.ts @@ -1,15 +1,14 @@ +import { describe, it } from 'node:test'; import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; -import { setUserAgentPlugin } from '../../src/setUserAgentPlugin.js'; +import { setUserAgentPlugin } from '../../dist/setUserAgentPlugin.js'; describe('setUserAgentPlugin', function test() { - this.timeout(20000); - it('can set the user agent on puppeteer', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [chromeLauncher()], plugins: [setUserAgentPlugin()], }); diff --git a/packages/test-runner-commands/test/set-viewport/setViewportPlugin.test.ts b/packages/test-runner-commands/test/set-viewport/setViewportPlugin.test.ts index 565efe6ffb..a0249cee32 100644 --- a/packages/test-runner-commands/test/set-viewport/setViewportPlugin.test.ts +++ b/packages/test-runner-commands/test/set-viewport/setViewportPlugin.test.ts @@ -1,17 +1,16 @@ +import { describe, it } from 'node:test'; import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; import { playwrightLauncher } from '@web/test-runner-playwright'; -import { setViewportPlugin } from '../../src/setViewportPlugin.js'; +import { setViewportPlugin } from '../../dist/setViewportPlugin.js'; describe('setViewportPlugin', function test() { - this.timeout(20000); - it('can set the viewport on puppeteer', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [chromeLauncher()], plugins: [setViewportPlugin()], }); @@ -19,7 +18,7 @@ describe('setViewportPlugin', function test() { it('can set the viewport on playwright', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [ playwrightLauncher({ product: 'chromium' }), playwrightLauncher({ product: 'firefox' }), diff --git a/packages/test-runner-commands/test/snapshot/snapshotPlugin.test.ts b/packages/test-runner-commands/test/snapshot/snapshotPlugin.test.ts index 4d52f8ca32..1712ff8e53 100644 --- a/packages/test-runner-commands/test/snapshot/snapshotPlugin.test.ts +++ b/packages/test-runner-commands/test/snapshot/snapshotPlugin.test.ts @@ -1,15 +1,14 @@ +import { describe, it } from 'node:test'; import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; import { playwrightLauncher } from '@web/test-runner-playwright'; -import { snapshotPlugin } from '../../src/snapshotPlugin.js'; +import { snapshotPlugin } from '../../dist/snapshotPlugin.js'; describe('snapshotPlugin', function test() { - this.timeout(20000); - it('passes snapshot tests', async () => { await runTests({ - files: [path.join(__dirname, 'browser-test.js')], + files: [path.join(import.meta.dirname, 'browser-test.js')], browsers: [ playwrightLauncher({ product: 'firefox' }), playwrightLauncher({ product: 'chromium' }), @@ -19,7 +18,7 @@ describe('snapshotPlugin', function test() { }); await runTests({ - files: [path.join(__dirname, 'src', 'nested-test.js')], + files: [path.join(import.meta.dirname, 'src', 'nested-test.js')], browsers: [ playwrightLauncher({ product: 'firefox' }), playwrightLauncher({ product: 'chromium' }), diff --git a/packages/test-runner-core/package.json b/packages/test-runner-core/package.json index f4f36f156d..79bb5e639a 100644 --- a/packages/test-runner-core/package.json +++ b/packages/test-runner-core/package.json @@ -33,8 +33,8 @@ }, "scripts": { "build": "tsc", - "test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", - "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/test-runner-core/test/src/runner/TestRunner.test.ts b/packages/test-runner-core/test/src/runner/TestRunner.test.ts index 9471a71f11..ac7251c115 100644 --- a/packages/test-runner-core/test/src/runner/TestRunner.test.ts +++ b/packages/test-runner-core/test/src/runner/TestRunner.test.ts @@ -1,50 +1,36 @@ -import * as hanbi from 'hanbi'; -import { expect } from 'chai'; +import { mock } from 'node:test'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import portfinder from 'portfinder'; import path from 'path'; -import { BrowserLauncher } from '../../../src/browser-launcher/BrowserLauncher.js'; -import { TestRunnerCoreConfig } from '../../../src/config/TestRunnerCoreConfig.js'; -import { TestRunner } from '../../../src/runner/TestRunner.js'; -import { Logger } from '../../../src/logger/Logger.js'; -import { SESSION_STATUS } from '../../../src/test-session/TestSessionStatus.js'; -import { TestRunnerGroupConfig } from '../../../src/index.js'; +import type { BrowserLauncher } from '../../../dist/browser-launcher/BrowserLauncher.js'; +import type { TestRunnerCoreConfig } from '../../../dist/config/TestRunnerCoreConfig.js'; +import { TestRunner } from '../../../dist/runner/TestRunner.js'; +import type { Logger } from '../../../dist/logger/Logger.js'; +import { SESSION_STATUS } from '../../../dist/test-session/TestSessionStatus.js'; +import type { TestRunnerGroupConfig } from '../../../dist/index.js'; -interface BrowserStubs { - stop: hanbi.Stub>; - startDebugSession: hanbi.Stub; - startSession: hanbi.Stub; - stopSession: hanbi.Stub; - isActive: hanbi.Stub; - getBrowserUrl: hanbi.Stub; -} - -function createBrowserStub(): [BrowserStubs, BrowserLauncher] { +function createBrowserStub(): [Record>, BrowserLauncher] { const spies = { - stop: hanbi.spy(), - getBrowserUrl: hanbi.spy(), - startDebugSession: hanbi.spy(), - startSession: hanbi.spy(), - stopSession: hanbi.spy(), - isActive: hanbi.spy(), + stop: mock.fn(() => Promise.resolve()), + getBrowserUrl: mock.fn(() => ''), + startDebugSession: mock.fn(() => Promise.resolve()), + startSession: mock.fn(() => Promise.resolve()), + stopSession: mock.fn(() => Promise.resolve({})), + isActive: mock.fn(() => true), }; - spies.stop.returns(Promise.resolve()); - spies.getBrowserUrl.returns(''); - spies.startDebugSession.returns(Promise.resolve()); - spies.startSession.returns(Promise.resolve()); - spies.stopSession.returns(Promise.resolve({})); - spies.isActive.returns(true); return [ spies, { name: 'myBrowser', type: 'myBrowser', - stop: spies.stop.handler, - getBrowserUrl: spies.getBrowserUrl.handler, - startDebugSession: spies.startDebugSession.handler, - startSession: spies.startSession.handler, - stopSession: spies.stopSession.handler, - isActive: spies.isActive.handler, + stop: spies.stop, + getBrowserUrl: spies.getBrowserUrl, + startDebugSession: spies.startDebugSession, + startSession: spies.startSession, + stopSession: spies.stopSession, + isActive: spies.isActive, }, ]; } @@ -69,13 +55,13 @@ async function createTestRunner( const [browserStubs, browser] = createBrowserStub(); - console.log(path.resolve(__dirname, '..', '..', '..', '..', '..')); + console.log(path.resolve(import.meta.dirname, '..', '..', '..', '..', '..')); const config: TestRunnerCoreConfig = { - files: [path.resolve(__dirname, '..', '..', 'fixtures', 'a.test.js')], + files: [path.resolve(import.meta.dirname, '..', '..', 'fixtures', 'a.test.js')], reporters: [], logger, - rootDir: path.resolve(__dirname, '..', '..', '..', '..', '..'), + rootDir: path.resolve(import.meta.dirname, '..', '..', '..', '..', '..'), testFramework: { path: 'my-framework.js' }, concurrentBrowsers: 2, concurrency: 10, @@ -97,16 +83,16 @@ async function createTestRunner( return { runner, browser, browserStubs }; } -describe('TestRunner', function () { +describe('TestRunner', () => { it('can run a single test file', async () => { const { runner, browserStubs } = await createTestRunner(); await runner.start(); - expect(runner.started).to.equal(true, 'runner is started'); - expect(browserStubs.startSession.callCount).to.equal(1); + assert.equal(runner.started, true, 'runner is started'); + assert.equal(browserStubs.startSession.mock.callCount(), 1); const sessions = Array.from(runner.sessions.all()); - expect(sessions.length).to.equal(1, 'one session is created'); + assert.equal(sessions.length, 1, 'one session is created'); await runner.stop(); }); @@ -130,9 +116,9 @@ describe('TestRunner', function () { const passed = await stopped; - expect(browserStubs.stopSession.callCount).to.equal(1, 'browser session is stopped'); - expect(browserStubs.stop.callCount).to.equal(1, 'browser is stopped'); - expect(passed).to.equal(true, 'test runner quits with true'); + assert.equal(browserStubs.stopSession.mock.callCount(), 1, 'browser session is stopped'); + assert.equal(browserStubs.stop.mock.callCount(), 1, 'browser is stopped'); + assert.equal(passed, true, 'test runner quits with true'); }); it('closes test runner for a failed test', async () => { @@ -154,9 +140,9 @@ describe('TestRunner', function () { runner.sessions.updateStatus({ ...sessions[0], passed: false }, SESSION_STATUS.TEST_FINISHED); const passed = await stopped; - expect(browserStubs.stopSession.callCount).to.equal(1, 'browser session is stopped'); - expect(browserStubs.stop.callCount).to.equal(1, 'browser is stopped'); - expect(passed).to.equal(false, 'test runner quits with false'); + assert.equal(browserStubs.stopSession.mock.callCount(), 1, 'browser session is stopped'); + assert.equal(browserStubs.stop.mock.callCount(), 1, 'browser is stopped'); + assert.equal(passed, false, 'test runner quits with false'); }); describe('groups', () => { @@ -164,14 +150,14 @@ describe('TestRunner', function () { const { runner } = await createTestRunner(undefined, [ { name: 'a', - files: [path.join(__dirname, '..', '..', 'fixtures', 'group-a', '*.test.js')], + files: [path.join(import.meta.dirname, '..', '..', 'fixtures', 'group-a', '*.test.js')], }, ]); const sessions = Array.from(runner.sessions.all()); - expect(sessions.length).to.equal(3); - expect(sessions.filter(s => s.group.name === 'default').length).to.equal(1); - expect(sessions.filter(s => s.group.name === 'a').length).to.equal(2); + assert.equal(sessions.length, 3); + assert.equal(sessions.filter(s => s.group.name === 'default').length, 1); + assert.equal(sessions.filter(s => s.group.name === 'a').length, 2); }); it('can create a group with a custom browser, inheriting test files', async () => { @@ -184,15 +170,15 @@ describe('TestRunner', function () { ]); const sessions = Array.from(runner.sessions.all()); - expect(sessions.length).to.equal(2); - expect(sessions.filter(s => s.group.name === 'default').length).to.equal(1); - expect(sessions.filter(s => s.group.name === 'a').length).to.equal(1); + assert.equal(sessions.length, 2); + assert.equal(sessions.filter(s => s.group.name === 'default').length, 1); + assert.equal(sessions.filter(s => s.group.name === 'a').length, 1); const sessionDefault = sessions.find(s => s.group.name === 'default')!; const sessionA = sessions.find(s => s.group.name === 'a')!; - expect(sessionDefault.testFile).to.equal(sessionA.testFile); - expect(sessionDefault.browser).to.equal(browser); - expect(sessionA.browser).to.equal(groupBrowser); + assert.equal(sessionDefault.testFile, sessionA.testFile); + assert.equal(sessionDefault.browser, browser); + assert.equal(sessionA.browser, groupBrowser); }); it('can create test groups inheriting browser', async () => { @@ -203,24 +189,24 @@ describe('TestRunner', function () { [ { name: 'a', - files: [path.join(__dirname, '..', '..', 'fixtures', 'group-a', '*.test.js')], + files: [path.join(import.meta.dirname, '..', '..', 'fixtures', 'group-a', '*.test.js')], }, { name: 'b', - files: [path.join(__dirname, '..', '..', 'fixtures', 'group-b', '*.test.js')], + files: [path.join(import.meta.dirname, '..', '..', 'fixtures', 'group-b', '*.test.js')], }, { name: 'c', - files: [path.join(__dirname, '..', '..', 'fixtures', 'group-c', '*.test.js')], + files: [path.join(import.meta.dirname, '..', '..', 'fixtures', 'group-c', '*.test.js')], }, ], ); const sessions = Array.from(runner.sessions.all()); - expect(sessions.length).to.equal(6); - expect(sessions.filter(s => s.group.name === 'a').length).to.equal(2); - expect(sessions.filter(s => s.group.name === 'b').length).to.equal(2); - expect(sessions.filter(s => s.group.name === 'c').length).to.equal(2); + assert.equal(sessions.length, 6); + assert.equal(sessions.filter(s => s.group.name === 'a').length, 2); + assert.equal(sessions.filter(s => s.group.name === 'b').length, 2); + assert.equal(sessions.filter(s => s.group.name === 'c').length, 2); }); it('can create test groups with custom browsers', async () => { @@ -232,20 +218,24 @@ describe('TestRunner', function () { [ { name: 'a', - files: [path.join(__dirname, '..', '..', 'fixtures', 'group-a', 'a-1.test.js')], + files: [ + path.join(import.meta.dirname, '..', '..', 'fixtures', 'group-a', 'a-1.test.js'), + ], }, { name: 'b', browsers: [browserB], - files: [path.join(__dirname, '..', '..', 'fixtures', 'group-b', 'b-1.test.js')], + files: [ + path.join(import.meta.dirname, '..', '..', 'fixtures', 'group-b', 'b-1.test.js'), + ], }, ], ); const sessions = Array.from(runner.sessions.all()); - expect(sessions.length).to.equal(2); - expect(sessions.find(s => s.group.name === 'a')!.browser).to.equal(browser); - expect(sessions.find(s => s.group.name === 'b')!.browser).to.equal(browserB); + assert.equal(sessions.length, 2); + assert.equal(sessions.find(s => s.group.name === 'a')!.browser, browser); + assert.equal(sessions.find(s => s.group.name === 'b')!.browser, browserB); }); it('can ignore files via string[] globs', async () => { @@ -255,8 +245,9 @@ describe('TestRunner', function () { }); const sessions = Array.from(runner.sessions.all()); - const allFiles = sessions.flatMap(x => path.relative(__dirname, x.testFile)); - expect(allFiles).to.deep.equal( + const allFiles = sessions.flatMap(x => path.relative(import.meta.dirname, x.testFile)); + assert.deepEqual( + allFiles, [ '../../fixtures/a.test.js', '../../fixtures/group-a/a-1.test.js', diff --git a/packages/test-runner-core/test/src/runner/TestScheduler.test.ts b/packages/test-runner-core/test/src/runner/TestScheduler.test.ts index 5433c76613..c5fc2dd9dc 100644 --- a/packages/test-runner-core/test/src/runner/TestScheduler.test.ts +++ b/packages/test-runner-core/test/src/runner/TestScheduler.test.ts @@ -1,27 +1,19 @@ -import { expect } from 'chai'; -import * as hanbi from 'hanbi'; +import assert from 'node:assert/strict'; +import { mock } from 'node:test'; +import { describe, it, beforeEach } from 'node:test'; -import { BrowserLauncher } from '../../../src/browser-launcher/BrowserLauncher.js'; +import type { BrowserLauncher } from '../../../dist/browser-launcher/BrowserLauncher.js'; -import { TestRunnerCoreConfig } from '../../../src/config/TestRunnerCoreConfig.js'; -import { TestScheduler } from '../../../src/runner/TestScheduler.js'; -import { TestSession } from '../../../src/test-session/TestSession.js'; -import { TestSessionManager } from '../../../src/test-session/TestSessionManager.js'; -import { SESSION_STATUS } from '../../../src/test-session/TestSessionStatus.js'; +import type { TestRunnerCoreConfig } from '../../../dist/config/TestRunnerCoreConfig.js'; +import { TestScheduler } from '../../../dist/runner/TestScheduler.js'; +import type { TestSession } from '../../../dist/test-session/TestSession.js'; +import { TestSessionManager } from '../../../dist/test-session/TestSessionManager.js'; +import { SESSION_STATUS } from '../../../dist/test-session/TestSessionStatus.js'; function timeout(ms = 0): Promise { return new Promise(r => setTimeout(r, ms)); } -interface BrowserStubs { - stop: hanbi.Stub>; - startDebugSession: hanbi.Stub; - startSession: hanbi.Stub; - stopSession: hanbi.Stub; - isActive: hanbi.Stub; - getBrowserUrl: hanbi.Stub; -} - describe('TestScheduler', () => { let mockConfig: TestRunnerCoreConfig; @@ -33,32 +25,28 @@ describe('TestScheduler', () => { } as Partial as TestSession; } - function createBrowserStub(name: string): [BrowserStubs, BrowserLauncher] { + function createBrowserStub( + name: string, + ): [Record>, BrowserLauncher] { const spies = { - stop: hanbi.spy(), - startDebugSession: hanbi.spy(), - startSession: hanbi.spy(), - stopSession: hanbi.spy(), - isActive: hanbi.spy(), - getBrowserUrl: hanbi.spy(), + stop: mock.fn(() => timeout(1)), + startDebugSession: mock.fn(() => timeout(1)), + startSession: mock.fn(() => timeout(1)), + stopSession: mock.fn(() => timeout(1).then(() => ({ testCoverage: {} }))), + isActive: mock.fn(() => true), + getBrowserUrl: mock.fn(() => ''), }; - spies.stop.returns(timeout(1)); - spies.startDebugSession.returns(timeout(1)); - spies.startSession.returns(timeout(1)); - spies.stopSession.returns(timeout(1).then(() => ({ testCoverage: {} }))); - spies.isActive.returns(true); - spies.getBrowserUrl.returns(''); return [ spies, { name, type: name, - stop: spies.stop.handler, - startDebugSession: spies.startDebugSession.handler, - startSession: spies.startSession.handler, - stopSession: spies.stopSession.handler, - isActive: spies.isActive.handler, - getBrowserUrl: spies.getBrowserUrl.handler, + stop: spies.stop, + startDebugSession: spies.startDebugSession, + startSession: spies.startSession, + stopSession: spies.stopSession, + isActive: spies.isActive, + getBrowserUrl: spies.getBrowserUrl, }, ]; } @@ -68,10 +56,10 @@ describe('TestScheduler', () => { rootDir: process.cwd(), logger: { ...console, - error(...args) { + error(...args: unknown[]) { console.error(...args); }, - logSyntaxError(error) { + logSyntaxError(error: unknown) { console.error(error); }, }, @@ -88,7 +76,12 @@ describe('TestScheduler', () => { function createTestFixture( ...ids: string[] - ): [TestScheduler, TestSessionManager, TestSession[], BrowserStubs] { + ): [ + TestScheduler, + TestSessionManager, + TestSession[], + Record>, + ] { const [browserStubs, browser] = createBrowserStub('a'); const sessions: TestSession[] = []; for (const id of ids) { @@ -106,14 +99,14 @@ describe('TestScheduler', () => { scheduler.schedule(1, [session1]); const finalSession1 = sessions.get(session1.id)!; - expect(finalSession1.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(stubs.startSession.callCount).to.equal(1); + assert.equal(finalSession1.status, SESSION_STATUS.INITIALIZING); + assert.equal(stubs.startSession.mock.callCount(), 1); }); it('when a session goes to status test finished, the browser is stopped and results is stored', async () => { const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); const testCoverage = {}; - stubs.stopSession.returns(timeout(1).then(() => ({ testCoverage }))); + stubs.stopSession.mock.mockImplementation(() => timeout(1).then(() => ({ testCoverage }))); scheduler.schedule(1, [session1]); await timeout(2); @@ -121,22 +114,22 @@ describe('TestScheduler', () => { await timeout(4); const finalSession1 = sessions.get(session1.id)!; - expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); - expect(finalSession1.passed).to.equal(true); - expect(finalSession1.testCoverage).to.equal(testCoverage); + assert.equal(finalSession1.status, SESSION_STATUS.FINISHED); + assert.equal(finalSession1.passed, true); + assert.equal(finalSession1.testCoverage, testCoverage); }); it('batches test execution', async () => { const [scheduler, sessions, sessionsToSchedule] = createTestFixture('1', '2', '3'); scheduler.schedule(1, sessionsToSchedule); - expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.SCHEDULED); + assert.equal(sessions.get('1')!.status, SESSION_STATUS.INITIALIZING); + assert.equal(sessions.get('2')!.status, SESSION_STATUS.INITIALIZING); + assert.equal(sessions.get('3')!.status, SESSION_STATUS.SCHEDULED); // wait for browser to start, session 3 should still not be started await timeout(2); - expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.SCHEDULED); + assert.equal(sessions.get('3')!.status, SESSION_STATUS.SCHEDULED); // mark tests as finished sessions.updateStatus({ ...sessions.get('1')!, passed: true }, SESSION_STATUS.TEST_FINISHED); @@ -146,13 +139,13 @@ describe('TestScheduler', () => { await timeout(4); // sessions 1 and 2 should be finished - expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.FINISHED); - expect(sessions.get('1')!.passed).to.be.true; - expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.FINISHED); - expect(sessions.get('2')!.passed).to.be.true; + assert.equal(sessions.get('1')!.status, SESSION_STATUS.FINISHED); + assert.equal(sessions.get('1')!.passed, true); + assert.equal(sessions.get('2')!.status, SESSION_STATUS.FINISHED); + assert.equal(sessions.get('2')!.passed, true); // session 3 should be started - expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.INITIALIZING); + assert.equal(sessions.get('3')!.status, SESSION_STATUS.INITIALIZING); }); it('scheduling new tests while executing keeps batching', async () => { @@ -162,17 +155,17 @@ describe('TestScheduler', () => { // schedule 2 sessions scheduler.schedule(1, sessionsToSchedule.slice(0, 2)); - expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.INITIALIZING); + assert.equal(sessions.get('1')!.status, SESSION_STATUS.INITIALIZING); + assert.equal(sessions.get('2')!.status, SESSION_STATUS.INITIALIZING); // schedule 3 more sessions after browser starts await timeout(4); scheduler.schedule(1, sessionsToSchedule.slice(2, 5)); - expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.SCHEDULED); - expect(sessions.get('4')!.status).to.equal(SESSION_STATUS.SCHEDULED); - expect(sessions.get('5')!.status).to.equal(SESSION_STATUS.SCHEDULED); + assert.equal(sessions.get('1')!.status, SESSION_STATUS.INITIALIZING); + assert.equal(sessions.get('2')!.status, SESSION_STATUS.INITIALIZING); + assert.equal(sessions.get('3')!.status, SESSION_STATUS.SCHEDULED); + assert.equal(sessions.get('4')!.status, SESSION_STATUS.SCHEDULED); + assert.equal(sessions.get('5')!.status, SESSION_STATUS.SCHEDULED); // mark first test as finished sessions.updateStatus({ ...sessions.get('1')!, passed: true }, SESSION_STATUS.TEST_FINISHED); @@ -181,12 +174,12 @@ describe('TestScheduler', () => { await timeout(4); // session 1 is finished, session 2 is still waiting, session 3 is now starting and the rest is still scheduled - expect(sessions.get('1')!.status).to.equal(SESSION_STATUS.FINISHED); - expect(sessions.get('1')!.passed).to.be.true; - expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(sessions.get('4')!.status).to.equal(SESSION_STATUS.SCHEDULED); - expect(sessions.get('5')!.status).to.equal(SESSION_STATUS.SCHEDULED); + assert.equal(sessions.get('1')!.status, SESSION_STATUS.FINISHED); + assert.equal(sessions.get('1')!.passed, true); + assert.equal(sessions.get('2')!.status, SESSION_STATUS.INITIALIZING); + assert.equal(sessions.get('3')!.status, SESSION_STATUS.INITIALIZING); + assert.equal(sessions.get('4')!.status, SESSION_STATUS.SCHEDULED); + assert.equal(sessions.get('5')!.status, SESSION_STATUS.SCHEDULED); // mark 2 and 3 as finished await timeout(2); @@ -195,28 +188,28 @@ describe('TestScheduler', () => { // 2 and 3 finish when browser closes await timeout(2); - expect(sessions.get('2')!.status).to.equal(SESSION_STATUS.FINISHED); - expect(sessions.get('3')!.status).to.equal(SESSION_STATUS.FINISHED); + assert.equal(sessions.get('2')!.status, SESSION_STATUS.FINISHED); + assert.equal(sessions.get('3')!.status, SESSION_STATUS.FINISHED); }); it('error while starting browser marks session as failed', async () => { const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); - stubs.startSession.callsFake(() => Promise.reject(new Error('mock error'))); + stubs.startSession.mock.mockImplementation(() => Promise.reject(new Error('mock error'))); scheduler.schedule(1, [session1]); await timeout(4); const finalSession1 = sessions.get(session1.id)!; - expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); - expect(finalSession1.passed).to.equal(false); - expect(finalSession1.errors.length).to.equal(1); - expect(finalSession1.errors[0].message).to.equal('mock error'); + assert.equal(finalSession1.status, SESSION_STATUS.FINISHED); + assert.equal(finalSession1.passed, false); + assert.equal(finalSession1.errors.length, 1); + assert.equal(finalSession1.errors[0].message, 'mock error'); }); it('error while starting browser after a session changed state gets logged', async () => { - const errorStub = hanbi.stubMethod(mockConfig.logger, 'error'); + const errorStub = mock.method(mockConfig.logger, 'error'); const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); - stubs.startSession.returns( + stubs.startSession.mock.mockImplementation(() => timeout(5).then(() => { throw new Error('mock error'); }), @@ -228,19 +221,20 @@ describe('TestScheduler', () => { await timeout(2); const finalSession1 = sessions.get(session1.id)!; - expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); - expect(finalSession1.passed).to.equal(true); + assert.equal(finalSession1.status, SESSION_STATUS.FINISHED); + assert.equal(finalSession1.passed, true); await timeout(20); - expect(errorStub.callCount).to.equal(1); - expect(errorStub.getCall(0).args[0]).to.an.instanceof(Error); - expect((errorStub.getCall(0).args[0] as Error).message).to.equal('mock error'); + assert.equal(errorStub.mock.callCount(), 1); + assert.ok(errorStub.mock.calls[0].arguments[0] instanceof Error); + assert.equal((errorStub.mock.calls[0].arguments[0] as Error).message, 'mock error'); + mock.restoreAll(); }); it('error while stopping browser marks session as failed', async () => { const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); - stubs.stopSession.callsFake(() => Promise.reject(new Error('mock error'))); + stubs.stopSession.mock.mockImplementation(() => Promise.reject(new Error('mock error'))); scheduler.schedule(1, [session1]); await timeout(2); @@ -248,26 +242,27 @@ describe('TestScheduler', () => { await timeout(4); const finalSession1 = sessions.get(session1.id)!; - expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); - expect(finalSession1.passed).to.equal(false); - expect(finalSession1.errors.length).to.equal(1); - expect(finalSession1.errors[0].message).to.equal('mock error'); + assert.equal(finalSession1.status, SESSION_STATUS.FINISHED); + assert.equal(finalSession1.passed, false); + assert.equal(finalSession1.errors.length, 1); + assert.equal(finalSession1.errors[0].message, 'mock error'); }); it('timeout starting the browser marks the session as failed', async () => { - mockConfig.browserStartTimeout = 2; + mockConfig.browserStartTimeout = 20; const [scheduler, sessions, [session1], stubs] = createTestFixture('1'); - stubs.startSession.returns(timeout(4)); + stubs.startSession.mock.mockImplementation(() => timeout(100)); scheduler.schedule(1, [session1]); - await timeout(3); + await timeout(50); const finalSession1 = sessions.get(session1.id)!; - expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); - expect(finalSession1.passed).to.equal(false); - expect(finalSession1.errors.length).to.equal(1); - expect(finalSession1.errors[0].message).to.equal( - 'The browser was unable to create and start a test page after 2ms. You can increase this timeout with the browserStartTimeout option.', + assert.equal(finalSession1.status, SESSION_STATUS.FINISHED); + assert.equal(finalSession1.passed, false); + assert.equal(finalSession1.errors.length, 1); + assert.equal( + finalSession1.errors[0].message, + 'The browser was unable to create and start a test page after 20ms. You can increase this timeout with the browserStartTimeout option.', ); }); @@ -279,10 +274,11 @@ describe('TestScheduler', () => { await timeout(20); const finalSession1 = sessions.get(session1.id)!; - expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); - expect(finalSession1.passed).to.equal(false); - expect(finalSession1.errors.length).to.equal(1); - expect(finalSession1.errors[0].message).to.equal( + assert.equal(finalSession1.status, SESSION_STATUS.FINISHED); + assert.equal(finalSession1.passed, false); + assert.equal(finalSession1.errors.length, 1); + assert.equal( + finalSession1.errors[0].message, 'Browser tests did not start after 2ms You can increase this timeout with the testsStartTimeout option. Check the browser logs or open the browser in debug mode for more information.', ); }); @@ -297,10 +293,11 @@ describe('TestScheduler', () => { await timeout(4); const finalSession1 = sessions.get(session1.id)!; - expect(finalSession1.status).to.equal(SESSION_STATUS.FINISHED); - expect(finalSession1.passed).to.equal(false); - expect(finalSession1.errors.length).to.equal(1); - expect(finalSession1.errors[0].message).to.equal( + assert.equal(finalSession1.status, SESSION_STATUS.FINISHED); + assert.equal(finalSession1.passed, false); + assert.equal(finalSession1.errors.length, 1); + assert.equal( + finalSession1.errors[0].message, 'Browser tests did not finish within 2ms. You can increase this timeout with the testsFinishTimeout option. Check the browser logs or open the browser in debug mode for more information.', ); }); @@ -309,8 +306,13 @@ describe('TestScheduler', () => { describe('multi browsers', () => { function createTestFixture( fixtures: { name: string; ids: string[] }[], - ): [TestScheduler, TestSessionManager, Array<[BrowserStubs, BrowserLauncher]>, TestSession[]] { - const browsers: Array<[BrowserStubs, BrowserLauncher]> = []; + ): [ + TestScheduler, + TestSessionManager, + Array<[Record>, BrowserLauncher]>, + TestSession[], + ] { + const browsers: Array<[Record>, BrowserLauncher]> = []; const sessions: TestSession[] = []; for (const fixture of fixtures) { @@ -343,35 +345,35 @@ describe('TestScheduler', () => { const session1 = sessionManager.get('1')!; const session2 = sessionManager.get('2')!; const session3 = sessionManager.get('3')!; - expect(session1.browser).to.equal(browsers[0][1]); - expect(session2.browser).to.equal(browsers[0][1]); - expect(session3.browser).to.equal(browsers[0][1]); - expect(session1.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(session2.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(session3.status).to.equal(SESSION_STATUS.SCHEDULED); - expect(browsers[0][0].startSession.callCount).to.equal(2); + assert.equal(session1.browser, browsers[0][1]); + assert.equal(session2.browser, browsers[0][1]); + assert.equal(session3.browser, browsers[0][1]); + assert.equal(session1.status, SESSION_STATUS.INITIALIZING); + assert.equal(session2.status, SESSION_STATUS.INITIALIZING); + assert.equal(session3.status, SESSION_STATUS.SCHEDULED); + assert.equal(browsers[0][0].startSession.mock.callCount(), 2); const session4 = sessionManager.get('4')!; const session5 = sessionManager.get('5')!; const session6 = sessionManager.get('6')!; - expect(session4.browser).to.equal(browsers[1][1]); - expect(session5.browser).to.equal(browsers[1][1]); - expect(session6.browser).to.equal(browsers[1][1]); - expect(session4.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(session5.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(session6.status).to.equal(SESSION_STATUS.SCHEDULED); - expect(browsers[1][0].startSession.callCount).to.equal(2); + assert.equal(session4.browser, browsers[1][1]); + assert.equal(session5.browser, browsers[1][1]); + assert.equal(session6.browser, browsers[1][1]); + assert.equal(session4.status, SESSION_STATUS.INITIALIZING); + assert.equal(session5.status, SESSION_STATUS.INITIALIZING); + assert.equal(session6.status, SESSION_STATUS.SCHEDULED); + assert.equal(browsers[1][0].startSession.mock.callCount(), 2); const session7 = sessionManager.get('7')!; const session8 = sessionManager.get('8')!; const session9 = sessionManager.get('9')!; - expect(session7.browser).to.equal(browsers[2][1]); - expect(session8.browser).to.equal(browsers[2][1]); - expect(session9.browser).to.equal(browsers[2][1]); - expect(session7.status).to.equal(SESSION_STATUS.SCHEDULED); - expect(session8.status).to.equal(SESSION_STATUS.SCHEDULED); - expect(session9.status).to.equal(SESSION_STATUS.SCHEDULED); - expect(browsers[2][0].startSession.called).to.equal(false); + assert.equal(session7.browser, browsers[2][1]); + assert.equal(session8.browser, browsers[2][1]); + assert.equal(session9.browser, browsers[2][1]); + assert.equal(session7.status, SESSION_STATUS.SCHEDULED); + assert.equal(session8.status, SESSION_STATUS.SCHEDULED); + assert.equal(session9.status, SESSION_STATUS.SCHEDULED); + assert.equal(browsers[2][0].startSession.mock.callCount() > 0, false); }); it('finishing a test schedules a new one', async () => { @@ -387,9 +389,9 @@ describe('TestScheduler', () => { await timeout(4); const session3 = sessionManager.get('3')!; - expect(session3.browser).to.equal(browsers[0][1]); - expect(session3.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(browsers[0][0].startSession.callCount).to.equal(3); + assert.equal(session3.browser, browsers[0][1]); + assert.equal(session3.status, SESSION_STATUS.INITIALIZING); + assert.equal(browsers[0][0].startSession.mock.callCount(), 3); }); it('overflow of concurrency budget does not trigger a new browser to start', async () => { @@ -406,9 +408,9 @@ describe('TestScheduler', () => { await timeout(4); const session7 = sessionManager.get('7')!; - expect(session7.browser).to.equal(browsers[2][1]); - expect(session7.status).to.equal(SESSION_STATUS.SCHEDULED); - expect(browsers[2][0].startSession.called).to.equal(false); + assert.equal(session7.browser, browsers[2][1]); + assert.equal(session7.status, SESSION_STATUS.SCHEDULED); + assert.equal(browsers[2][0].startSession.mock.callCount() > 0, false); }); it('finishing one browsers schedules a new browser', async () => { @@ -427,9 +429,9 @@ describe('TestScheduler', () => { await timeout(4); const session7 = sessionManager.get('7')!; - expect(session7.browser).to.equal(browsers[2][1]); - expect(session7.status).to.equal(SESSION_STATUS.INITIALIZING); - expect(browsers[2][0].startSession.callCount).to.equal(2); + assert.equal(session7.browser, browsers[2][1]); + assert.equal(session7.status, SESSION_STATUS.INITIALIZING); + assert.equal(browsers[2][0].startSession.mock.callCount(), 2); }); }); }); diff --git a/packages/test-runner-junit-reporter/package.json b/packages/test-runner-junit-reporter/package.json index 266337955e..c402fb4275 100644 --- a/packages/test-runner-junit-reporter/package.json +++ b/packages/test-runner-junit-reporter/package.json @@ -26,8 +26,8 @@ }, "scripts": { "build": "tsc", - "test": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", - "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test --reporter dot" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/test-runner-junit-reporter/test/junitReporter.test.ts b/packages/test-runner-junit-reporter/test/junitReporter.test.ts index 79e63fed3e..9421315aff 100644 --- a/packages/test-runner-junit-reporter/test/junitReporter.test.ts +++ b/packages/test-runner-junit-reporter/test/junitReporter.test.ts @@ -1,18 +1,19 @@ -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it, after } from 'node:test'; import { promises as fs } from 'fs'; import path from 'path'; import globby from 'globby'; import { chromeLauncher } from '@web/test-runner-chrome'; -import { TestRunnerCoreConfig } from '@web/test-runner-core'; +import type { TestRunnerCoreConfig } from '@web/test-runner-core'; import { runTests } from '@web/test-runner-core/test-helpers'; -import { junitReporter } from '../src/junitReporter.js'; +import { junitReporter } from '../dist/junitReporter.js'; const NON_ZERO_TIME_VALUE_REGEX = /time="((\d\.\d+)|(\d))"/g; const USER_AGENT_STRING_REGEX = /"Mozilla\/5\.0 (.*)"/g; -const rootDir = path.join(__dirname, '..', '..', '..'); +const rootDir = path.join(import.meta.dirname, '..', '..', '..'); const normalizeOutput = (cwd: string, output: string) => output @@ -20,11 +21,11 @@ const normalizeOutput = (cwd: string, output: string) => .replace(USER_AGENT_STRING_REGEX, '"<>"') .replace(/(Context|n)./g, '<>') // don't judge - normalizing paths for windblows - .replace(/\/>/g, '🙈>') - .replace(/<\//g, '<🙈') + .replace(/\/>/g, '\u{1F648}>') + .replace(/<\//g, '<\u{1F648}') .replace(/\//g, path.sep) - .replace(/🙈>/g, '/>') - .replace(/<🙈/g, '/g, '/>') + .replace(/<\u{1F648}/g, ' => @@ -64,35 +65,35 @@ async function run(cwd: string): Promise<{ actual: string; expected: string }> { async function cleanupFixtures() { for (const file of await globby('fixtures/**/test-results.xml', { absolute: true, - cwd: __dirname, + cwd: import.meta.dirname, })) await fs.unlink(file); } -describe('junitReporter', function () { +describe('junitReporter', { timeout: 60000 }, () => { after(cleanupFixtures); - describe('for a simple case', function () { - const fixtureDir = path.join(__dirname, 'fixtures/simple'); - it('produces expected results', async function () { + describe('for a simple case', () => { + const fixtureDir = path.join(import.meta.dirname, 'fixtures/simple'); + it('produces expected results', async () => { const { actual, expected } = await run(fixtureDir); - expect(actual).to.equal(expected); + assert.equal(actual, expected); }); }); - describe('for a nested suite', function () { - const fixtureDir = path.join(__dirname, 'fixtures/nested'); - it('produces expected results', async function () { + describe('for a nested suite', () => { + const fixtureDir = path.join(import.meta.dirname, 'fixtures/nested'); + it('produces expected results', async () => { const { actual, expected } = await run(fixtureDir); - expect(actual).to.equal(expected); + assert.equal(actual, expected); }); }); - describe('for multiple test files', function () { - const fixtureDir = path.join(__dirname, 'fixtures/multiple'); - it('produces expected results', async function () { + describe('for multiple test files', () => { + const fixtureDir = path.join(import.meta.dirname, 'fixtures/multiple'); + it('produces expected results', async () => { const { actual, expected } = await run(fixtureDir); - expect(actual).to.equal(expected); + assert.equal(actual, expected); }); }); }); diff --git a/packages/test-runner-mocha/package.json b/packages/test-runner-mocha/package.json index 85ed614e43..965c3e0d20 100644 --- a/packages/test-runner-mocha/package.json +++ b/packages/test-runner-mocha/package.json @@ -20,8 +20,8 @@ "scripts": { "build": "tsc", "build:production": "rimraf dist && rollup -c ./rollup.config.mjs", - "test": "mocha test/**/*.test.js --reporter dot", - "test:watch": "mocha test/**/*.test.js --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.js", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.js" }, "files": [ "dist" diff --git a/packages/test-runner-mocha/test/autorun.test.js b/packages/test-runner-mocha/test/autorun.test.js index 155b24937a..2f1ce090fb 100644 --- a/packages/test-runner-mocha/test/autorun.test.js +++ b/packages/test-runner-mocha/test/autorun.test.js @@ -1,11 +1,10 @@ +const { it } = require('node:test'); +const assert = require('node:assert/strict'); const { runTests } = require('@web/test-runner-core/test-helpers'); const { chromeLauncher } = require('@web/test-runner-chrome'); const { resolve } = require('path'); -const { expect } = require('chai'); - -it('can run tests with autorun', async function () { - this.timeout(50000); +it('can run tests with autorun', { timeout: 50000 }, async () => { const { sessions } = await runTests( { files: [resolve(__dirname, 'fixtures', 'autorun.js')], @@ -16,28 +15,28 @@ it('can run tests with autorun', async function () { { allowFailure: true, reportErrors: false }, ); - expect(sessions.length).to.equal(1); - expect(sessions[0].passed).to.equal(false); + assert.equal(sessions.length, 1); + assert.equal(sessions[0].passed, false); - expect(sessions[0].testResults.tests.length).to.equal(2); - expect(sessions[0].testResults.tests[0].name).to.equal('test 1'); - expect(sessions[0].testResults.tests[0].passed).to.equal(true); - expect(sessions[0].testResults.tests[1].name).to.equal('test 2'); - expect(sessions[0].testResults.tests[1].passed).to.equal(false); - expect(sessions[0].testResults.tests[1].error.message).to.equal('test 2 error'); + assert.equal(sessions[0].testResults.tests.length, 2); + assert.equal(sessions[0].testResults.tests[0].name, 'test 1'); + assert.equal(sessions[0].testResults.tests[0].passed, true); + assert.equal(sessions[0].testResults.tests[1].name, 'test 2'); + assert.equal(sessions[0].testResults.tests[1].passed, false); + assert.equal(sessions[0].testResults.tests[1].error.message, 'test 2 error'); - expect(sessions[0].testResults.suites.length).to.equal(1); - expect(sessions[0].testResults.suites[0].tests.length).to.equal(2); - expect(sessions[0].testResults.suites[0].tests[0].name).to.equal('test a 1'); - expect(sessions[0].testResults.suites[0].tests[0].passed).to.equal(true); - expect(sessions[0].testResults.suites[0].tests[1].name).to.equal('test a 2'); - expect(sessions[0].testResults.suites[0].tests[1].passed).to.equal(false); - expect(sessions[0].testResults.suites[0].tests[1].error.message).to.equal('test a 2 error'); + assert.equal(sessions[0].testResults.suites.length, 1); + assert.equal(sessions[0].testResults.suites[0].tests.length, 2); + assert.equal(sessions[0].testResults.suites[0].tests[0].name, 'test a 1'); + assert.equal(sessions[0].testResults.suites[0].tests[0].passed, true); + assert.equal(sessions[0].testResults.suites[0].tests[1].name, 'test a 2'); + assert.equal(sessions[0].testResults.suites[0].tests[1].passed, false); + assert.equal(sessions[0].testResults.suites[0].tests[1].error.message, 'test a 2 error'); - expect(sessions[0].testResults.suites[0].suites.length).to.equal(1); - expect(sessions[0].testResults.suites[0].suites[0].tests.length).to.equal(2); - expect(sessions[0].testResults.suites[0].suites[0].tests[0].name).to.equal('test b 1'); - expect(sessions[0].testResults.suites[0].suites[0].tests[0].passed).to.equal(true); - expect(sessions[0].testResults.suites[0].suites[0].tests[1].name).to.equal('test b 2'); - expect(sessions[0].testResults.suites[0].suites[0].tests[1].passed).to.equal(true); + assert.equal(sessions[0].testResults.suites[0].suites.length, 1); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests.length, 2); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests[0].name, 'test b 1'); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests[0].passed, true); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests[1].name, 'test b 2'); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests[1].passed, true); }); diff --git a/packages/test-runner-mocha/test/standalone.test.js b/packages/test-runner-mocha/test/standalone.test.js index 781d2a49fc..b1f78b72c1 100644 --- a/packages/test-runner-mocha/test/standalone.test.js +++ b/packages/test-runner-mocha/test/standalone.test.js @@ -1,11 +1,10 @@ +const { it } = require('node:test'); +const assert = require('node:assert/strict'); const { runTests } = require('@web/test-runner-core/test-helpers'); const { chromeLauncher } = require('@web/test-runner-chrome'); const { resolve } = require('path'); -const { expect } = require('chai'); - -it('can run tests with standalone', async function () { - this.timeout(50000); +it('can run tests with standalone', { timeout: 50000 }, async () => { const { sessions } = await runTests( { files: [resolve(__dirname, 'fixtures', 'standalone.html')], @@ -16,35 +15,33 @@ it('can run tests with standalone', async function () { { allowFailure: true, reportErrors: false }, ); - expect(sessions.length).to.equal(1); - expect(sessions[0].passed).to.equal(false); - - expect(sessions[0].testResults.tests.length).to.equal(2); - expect(sessions[0].testResults.tests[0].name).to.equal('test 1'); - expect(sessions[0].testResults.tests[0].passed).to.equal(true); - expect(sessions[0].testResults.tests[1].name).to.equal('test 2'); - expect(sessions[0].testResults.tests[1].passed).to.equal(false); - expect(sessions[0].testResults.tests[1].error.message).to.equal('test 2 error'); - - expect(sessions[0].testResults.suites.length).to.equal(1); - expect(sessions[0].testResults.suites[0].tests.length).to.equal(2); - expect(sessions[0].testResults.suites[0].tests[0].name).to.equal('test a 1'); - expect(sessions[0].testResults.suites[0].tests[0].passed).to.equal(true); - expect(sessions[0].testResults.suites[0].tests[1].name).to.equal('test a 2'); - expect(sessions[0].testResults.suites[0].tests[1].passed).to.equal(false); - expect(sessions[0].testResults.suites[0].tests[1].error.message).to.equal('test a 2 error'); - - expect(sessions[0].testResults.suites[0].suites.length).to.equal(1); - expect(sessions[0].testResults.suites[0].suites[0].tests.length).to.equal(2); - expect(sessions[0].testResults.suites[0].suites[0].tests[0].name).to.equal('test b 1'); - expect(sessions[0].testResults.suites[0].suites[0].tests[0].passed).to.equal(true); - expect(sessions[0].testResults.suites[0].suites[0].tests[1].name).to.equal('test b 2'); - expect(sessions[0].testResults.suites[0].suites[0].tests[1].passed).to.equal(true); + assert.equal(sessions.length, 1); + assert.equal(sessions[0].passed, false); + + assert.equal(sessions[0].testResults.tests.length, 2); + assert.equal(sessions[0].testResults.tests[0].name, 'test 1'); + assert.equal(sessions[0].testResults.tests[0].passed, true); + assert.equal(sessions[0].testResults.tests[1].name, 'test 2'); + assert.equal(sessions[0].testResults.tests[1].passed, false); + assert.equal(sessions[0].testResults.tests[1].error.message, 'test 2 error'); + + assert.equal(sessions[0].testResults.suites.length, 1); + assert.equal(sessions[0].testResults.suites[0].tests.length, 2); + assert.equal(sessions[0].testResults.suites[0].tests[0].name, 'test a 1'); + assert.equal(sessions[0].testResults.suites[0].tests[0].passed, true); + assert.equal(sessions[0].testResults.suites[0].tests[1].name, 'test a 2'); + assert.equal(sessions[0].testResults.suites[0].tests[1].passed, false); + assert.equal(sessions[0].testResults.suites[0].tests[1].error.message, 'test a 2 error'); + + assert.equal(sessions[0].testResults.suites[0].suites.length, 1); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests.length, 2); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests[0].name, 'test b 1'); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests[0].passed, true); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests[1].name, 'test b 2'); + assert.equal(sessions[0].testResults.suites[0].suites[0].tests[1].passed, true); }); -it('captures errors during setup', async function () { - this.timeout(50000); - +it('captures errors during setup', { timeout: 50000 }, async () => { const { sessions } = await runTests( { files: [resolve(__dirname, 'fixtures', 'standalone-setup-fail.html')], @@ -55,8 +52,8 @@ it('captures errors during setup', async function () { { allowFailure: true, reportErrors: false }, ); - expect(sessions.length).to.equal(1); - expect(sessions[0].passed).to.equal(false); - expect(sessions[0].errors.length).to.equal(1); - expect(sessions[0].errors[0].message).to.equal('error during setup'); + assert.equal(sessions.length, 1); + assert.equal(sessions[0].passed, false); + assert.equal(sessions[0].errors.length, 1); + assert.equal(sessions[0].errors[0].message, 'error during setup'); }); diff --git a/packages/test-runner-mocha/tsconfig.json b/packages/test-runner-mocha/tsconfig.json index 8eb7c546be..32a9e1eaef 100644 --- a/packages/test-runner-mocha/tsconfig.json +++ b/packages/test-runner-mocha/tsconfig.json @@ -7,7 +7,8 @@ "outDir": "./dist", "rootDir": "./src", "composite": true, - "allowJs": true + "allowJs": true, + "types": ["mocha"] }, "references": [ { @@ -23,13 +24,6 @@ "path": "../test-runner-core/tsconfig.json" } ], - "include": [ - "src", - "types" - ], - "exclude": [ - "src/browser", - "tests", - "dist" - ] -} \ No newline at end of file + "include": ["src", "types"], + "exclude": ["src/browser", "tests", "dist"] +} diff --git a/packages/test-runner-module-mocking/package.json b/packages/test-runner-module-mocking/package.json index f44bbcc275..0075e6c4d4 100644 --- a/packages/test-runner-module-mocking/package.json +++ b/packages/test-runner-module-mocking/package.json @@ -24,8 +24,8 @@ }, "scripts": { "build": "tsc", - "test:node": "mocha test/**/*.test.ts --loader=ts-node/esm --reporter dot", - "test:watch": "mocha test/**/*.test.ts --loader ts-node/esm --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", diff --git a/packages/test-runner-module-mocking/test/moduleMockingPlugin.test.ts b/packages/test-runner-module-mocking/test/moduleMockingPlugin.test.ts index 2b365dcc72..6ebc544801 100644 --- a/packages/test-runner-module-mocking/test/moduleMockingPlugin.test.ts +++ b/packages/test-runner-module-mocking/test/moduleMockingPlugin.test.ts @@ -4,14 +4,13 @@ import { runTests } from '@web/test-runner-core/test-helpers'; import { chromeLauncher } from '@web/test-runner-chrome'; import { nodeResolvePlugin } from '@web/dev-server'; -import { moduleMockingPlugin } from '../src/moduleMockingPlugin.js'; -import { expect } from 'chai'; +import { moduleMockingPlugin } from '../dist/moduleMockingPlugin.js'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; const dirname = fileURLToPath(new URL('.', import.meta.url)); -describe('moduleMockingPlugin', function test() { - this.timeout(20000); - +describe('moduleMockingPlugin', { timeout: 20000 }, () => { it('can intercept server relative modules', async () => { await runTests({ files: [path.join(dirname, 'fixtures', 'server-relative', 'browser-test.js')], @@ -43,11 +42,11 @@ describe('moduleMockingPlugin', function test() { { allowFailure: true, reportErrors: false }, ); - expect(sessions.length).to.equal(1); - expect(sessions[0].passed).to.equal(false); - expect(sessions[0].errors.length).to.equal(1); - expect(sessions[0].logs[0][0]).to.match(/Error: Module interception is not active./); - expect(sessions[0].errors[0].message).to.match(/Could not import your test module./); + assert.equal(sessions.length, 1); + assert.equal(sessions[0].passed, false); + assert.equal(sessions[0].errors.length, 1); + assert.match(sessions[0].logs[0][0], /Error: Module interception is not active./); + assert.match(sessions[0].errors[0].message, /Could not import your test module./); }); it('throws when trying to intercept an inexistent module', async () => { @@ -61,11 +60,11 @@ describe('moduleMockingPlugin', function test() { { allowFailure: true, reportErrors: false }, ); - expect(sessions.length).to.equal(1); - expect(sessions[0].passed).to.equal(false); - expect(sessions[0].errors.length).to.equal(1); - expect(sessions[0].logs[0][0]).to.match(/Error: Could not resolve "\/inexistent-module.js"./); - expect(sessions[0].errors[0].message).to.match(/Could not import your test module./); + assert.equal(sessions.length, 1); + assert.equal(sessions[0].passed, false); + assert.equal(sessions[0].errors.length, 1); + assert.match(sessions[0].logs[0][0], /Error: Could not resolve "\/inexistent-module.js"./); + assert.match(sessions[0].errors[0].message, /Could not import your test module./); }); it('throws when trying to intercept a relative module', async () => { @@ -79,12 +78,13 @@ describe('moduleMockingPlugin', function test() { { allowFailure: true, reportErrors: false }, ); - expect(sessions.length).to.equal(1); - expect(sessions[0].passed).to.equal(false); - expect(sessions[0].errors.length).to.equal(1); - expect(sessions[0].logs[0][0]).to.match( + assert.equal(sessions.length, 1); + assert.equal(sessions[0].passed, false); + assert.equal(sessions[0].errors.length, 1); + assert.match( + sessions[0].logs[0][0], /Error: Parameter `moduleName` \('.\/file\.js'\) contains a relative reference./, ); - expect(sessions[0].errors[0].message).to.match(/Could not import your test module./); + assert.match(sessions[0].errors[0].message, /Could not import your test module./); }); }); diff --git a/packages/test-runner-playwright/package.json b/packages/test-runner-playwright/package.json index d7429b9287..c82356b04e 100644 --- a/packages/test-runner-playwright/package.json +++ b/packages/test-runner-playwright/package.json @@ -25,9 +25,7 @@ "node": ">=22.0.0" }, "scripts": { - "build": "tsc", - "test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", - "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test" + "build": "tsc" }, "files": [ "*.d.ts", diff --git a/packages/test-runner-puppeteer/package.json b/packages/test-runner-puppeteer/package.json index 088d0262b2..5e455ee64a 100644 --- a/packages/test-runner-puppeteer/package.json +++ b/packages/test-runner-puppeteer/package.json @@ -25,9 +25,7 @@ "node": ">=22.0.0" }, "scripts": { - "build": "tsc", - "test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", - "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test" + "build": "tsc" }, "files": [ "*.d.ts", diff --git a/packages/test-runner-visual-regression/package.json b/packages/test-runner-visual-regression/package.json index 3db4aae8db..47485cc253 100644 --- a/packages/test-runner-visual-regression/package.json +++ b/packages/test-runner-visual-regression/package.json @@ -30,8 +30,8 @@ }, "scripts": { "build": "tsc", - "test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot", - "test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test" + "test:node": "node --test --test-force-exit test/**/*.test.ts", + "test:watch": "node --test --test-force-exit --watch test/**/*.test.ts" }, "files": [ "*.d.ts", @@ -61,7 +61,6 @@ "devDependencies": { "@web/test-runner-chrome": "^0.18.0", "@web/test-runner-playwright": "^0.11.0", - "@web/test-runner-webdriver": "^0.9.0", - "mocha": "^10.8.2" + "@web/test-runner-webdriver": "^0.9.0" } } diff --git a/packages/test-runner-visual-regression/test/visualRegressionPlugin.test.ts b/packages/test-runner-visual-regression/test/visualRegressionPlugin.test.ts index fa9606a474..0fee4e6023 100644 --- a/packages/test-runner-visual-regression/test/visualRegressionPlugin.test.ts +++ b/packages/test-runner-visual-regression/test/visualRegressionPlugin.test.ts @@ -1,18 +1,17 @@ import path from 'path'; import { runTests } from '@web/test-runner-core/test-helpers'; -import { expect } from 'chai'; +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; import { chromeLauncher } from '@web/test-runner-chrome'; -import { visualRegressionPlugin } from '../src/visualRegressionPlugin.js'; -import { fileExists } from '../src/fs.js'; +import { visualRegressionPlugin } from '../dist/visualRegressionPlugin.js'; +import { fileExists } from '../dist/fs.js'; import { playwrightLauncher } from '@web/test-runner-playwright'; -describe('visualRegressionPlugin', function test() { - this.timeout(20000); - +describe('visualRegressionPlugin', { timeout: 20000 }, () => { it('can run a passing test', async () => { await runTests({ - files: [path.join(__dirname, 'diff-pass-test.js')], + files: [path.join(import.meta.dirname, 'diff-pass-test.js')], browsers: [ chromeLauncher(), playwrightLauncher({ product: 'firefox' }), @@ -38,7 +37,7 @@ describe('visualRegressionPlugin', function test() { it('can run a failed test', async () => { const { sessions } = await runTests( { - files: [path.join(__dirname, 'diff-fail-test.js')], + files: [path.join(import.meta.dirname, 'diff-fail-test.js')], browsers: [ chromeLauncher(), playwrightLauncher({ product: 'firefox' }), @@ -63,18 +62,20 @@ describe('visualRegressionPlugin', function test() { { allowFailure: true, reportErrors: false }, ); - expect(sessions.length).to.equal(3); + assert.equal(sessions.length, 3); for (const session of sessions) { - expect(session.passed).to.equal(false); - expect(session.testResults!.tests.length).to.equal(1); - expect(session.testResults!.tests[0].error!.message).to.include( - 'Visual diff failed. New screenshot is ', + assert.equal(session.passed, false); + assert.equal(session.testResults!.tests.length, 1); + assert.ok( + session.testResults!.tests[0].error!.message.includes( + 'Visual diff failed. New screenshot is ', + ), ); - expect( + assert.equal( await fileExists( path.resolve( - __dirname, + import.meta.dirname, '..', 'screenshots', session.browser.name, @@ -82,11 +83,12 @@ describe('visualRegressionPlugin', function test() { 'my-failed-element.png', ), ), - ).to.equal(true); - expect( + true, + ); + assert.equal( await fileExists( path.resolve( - __dirname, + import.meta.dirname, '..', 'screenshots', session.browser.name, @@ -94,7 +96,8 @@ describe('visualRegressionPlugin', function test() { 'my-failed-element-diff.png', ), ), - ).to.equal(true); + true, + ); } }); }); diff --git a/tsconfig.browser-base.json b/tsconfig.browser-base.json index 4f9f096f34..7f7cd388c9 100644 --- a/tsconfig.browser-base.json +++ b/tsconfig.browser-base.json @@ -44,7 +44,7 @@ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ "typeRoots": ["@types", "./types"], - "types": ["mocha", "chai"] /* Type declaration files to be included in compilation. */, + "types": [] /* Type declaration files to be included in compilation. */, "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */, "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ diff --git a/tsconfig.node-base.json b/tsconfig.node-base.json index 2a3d218b54..845e10f069 100644 --- a/tsconfig.node-base.json +++ b/tsconfig.node-base.json @@ -1,7 +1,4 @@ { - "ts-node": { - "experimentalResolver": true - }, "compilerOptions": { /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ @@ -47,7 +44,7 @@ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ "typeRoots": ["@types", "./types"], - "types": ["node", "mocha", "chai"] /* Type declaration files to be included in compilation. */, + "types": ["node"] /* Type declaration files to be included in compilation. */, "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */, "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ @@ -64,7 +61,7 @@ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ "skipLibCheck": true, /* Advanced Options */ - "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */, "lib": [ "DOM", "DOM.Iterable",