From 2e7ce5fa9208974d7f30c7000f731a13f29763c6 Mon Sep 17 00:00:00 2001 From: CharlieHelps Date: Fri, 6 Mar 2026 01:45:56 +0000 Subject: [PATCH 1/3] test: migrate phase 2 packages from ava to vitest --- .config/vitest.config.mts | 17 +- packages/babel/package.json | 12 +- packages/babel/test/as-input-plugin.mjs | 496 +++++++++--------- packages/babel/test/as-output-plugin.mjs | 258 +++++---- packages/dynamic-import-vars/package.json | 13 +- .../rollup-plugin-dynamic-import-vars.test.js | 176 +++---- ...up-plugin-dynamic-import-vars.test.js.snap | Bin 1006 -> 7062 bytes .../test/src/dynamic-import-to-glob.test.mjs | 167 ++---- packages/esm-shim/package.json | 4 +- packages/esm-shim/test/snapshots/test.js.snap | Bin 624 -> 2525 bytes packages/esm-shim/test/test.js | 86 +-- packages/html/package.json | 15 +- packages/html/test/snapshots/test.js.snap | Bin 1673 -> 7606 bytes packages/html/test/test.js | 142 +++-- packages/json/package.json | 15 +- packages/json/test/snapshots/test.js.snap | Bin 531 -> 1417 bytes packages/json/test/test.js | 208 ++++---- packages/replace/package.json | 15 +- packages/replace/test/form.js | 11 +- packages/replace/test/function.js | 18 +- packages/replace/test/misc.js | 45 +- packages/replace/test/snapshots/form.js.snap | Bin 989 -> 2417 bytes packages/replace/test/snapshots/misc.js.snap | Bin 398 -> 523 bytes .../replace/test/snapshots/sourcemaps.js.snap | Bin 379 -> 1567 bytes packages/replace/test/sourcemaps.js | 113 ++-- packages/terser/package.json | 4 +- packages/terser/test/test.js | 318 ++++++----- packages/url/package.json | 16 +- packages/url/test/snapshots/test.js.snap | Bin 1204 -> 4712 bytes packages/url/test/test.js | 169 +++--- packages/wasm/package.json | 16 +- packages/wasm/test/snapshots/test.mjs.snap | Bin 265 -> 236 bytes packages/wasm/test/test.mjs | 224 ++++---- 33 files changed, 1297 insertions(+), 1261 deletions(-) diff --git a/.config/vitest.config.mts b/.config/vitest.config.mts index 525bae94c..45b02dccf 100644 --- a/.config/vitest.config.mts +++ b/.config/vitest.config.mts @@ -5,8 +5,21 @@ export default defineConfig({ test: { // Enable global APIs for CommonJS test files. globals: true, - // Phase 1 packages use runtime-style test entrypoints. - include: ['test/test.{js,mjs,cjs,ts,mts,cts}'], + // Phase 1/2 packages use runtime-style, *.test, and a few named entrypoints. + include: [ + 'test/test.{js,mjs,cjs,ts,mts,cts}', + 'test/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts}', + 'test/{as-input-plugin,as-output-plugin,form,function,misc,sourcemaps}.{js,mjs,cjs,ts,mts,cts}' + ], + exclude: [ + '**/test/fixtures/**', + '**/test/helpers/**', + '**/test/node_modules/**', + '**/test/recipes/**', + '**/test/output/**', + '**/test/snapshots/**', + '**/test/types.ts' + ], // Keep snapshots in the same location used by Ava. resolveSnapshotPath: (testPath, snapExt) => path.join(path.dirname(testPath), 'snapshots', path.basename(testPath) + snapExt) diff --git a/packages/babel/package.json b/packages/babel/package.json index d888f31e5..55bff366f 100644 --- a/packages/babel/package.json +++ b/packages/babel/package.json @@ -28,13 +28,13 @@ "ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov", "ci:lint": "pnpm build && pnpm lint", "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}", - "ci:test": "pnpm test -- --verbose", + "ci:test": "pnpm test -- --reporter=verbose", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", "prerelease": "pnpm build", "pretest": "pnpm build", "release": "pnpm --workspace-root package:release $(pwd)", - "test": "ava", + "test": "vitest --config ../../.config/vitest.config.mts run", "test:ts": "tsc types/index.d.ts test/types.ts --noEmit" }, "files": [ @@ -83,14 +83,6 @@ "source-map": "^0.7.4" }, "types": "./types/index.d.ts", - "ava": { - "files": [ - "!**/fixtures/**", - "!**/helpers/**", - "!**/recipes/**", - "!**/types.ts" - ] - }, "contributors": [ "Bogdan Chadkin ", "Mateusz Burzyński (https://github.com/Andarist)" diff --git a/packages/babel/test/as-input-plugin.mjs b/packages/babel/test/as-input-plugin.mjs index 4b8d9495f..08bfcfef4 100644 --- a/packages/babel/test/as-input-plugin.mjs +++ b/packages/babel/test/as-input-plugin.mjs @@ -1,10 +1,9 @@ import { createRequire } from 'node:module'; import * as nodePath from 'node:path'; import * as fs from 'node:fs'; - import { fileURLToPath } from 'url'; -import test from 'ava'; +import { test, expect } from 'vitest'; import { rollup } from 'rollup'; import jsonPlugin from '@rollup/plugin-json'; import nodeResolvePlugin from '@rollup/plugin-node-resolve'; @@ -16,28 +15,24 @@ import { getCode } from '../../../util/test.js'; const DIRNAME = fileURLToPath(new URL('.', import.meta.url)); const FIXTURES = `${DIRNAME}/fixtures/`; - function getLocation(source, charIndex) { const lines = source.split('\n'); const len = lines.length; - let lineStart = 0; - for (let i = 0; i < len; i += 1) { const line = lines[i]; // +1 for newline const lineEnd = lineStart + line.length + 1; - if (lineEnd > charIndex) { - return { line: i + 1, column: charIndex - lineStart }; + return { + line: i + 1, + column: charIndex - lineStart + }; } - lineStart = lineEnd; } - throw new Error('Could not determine location of character'); } - function replaceConsoleLogProperty({ types: t }) { return { name: 'replace-console-log-property', @@ -51,165 +46,161 @@ function replaceConsoleLogProperty({ types: t }) { } }; } - async function generate(input, babelOptions = {}, generateOptions = {}, rollupOptions = {}) { const bundle = await rollup({ input: FIXTURES + input, - plugins: [babelPlugin({ babelHelpers: 'bundled', ...babelOptions })], + plugins: [ + babelPlugin({ + babelHelpers: 'bundled', + ...babelOptions + }) + ], ...rollupOptions }); - return getCode(bundle, { format: 'cjs', exports: 'auto', ...generateOptions }); } - -test('runs code through babel', async (t) => { +test('runs code through babel', async () => { const code = await generate('basic/main.js'); - t.false(code.includes('const')); - t.is( - code, - `'use strict'; + expect(code.includes('const')).toBe(false); + expect(code).toBe(`'use strict'; var answer = 42; console.log("the answer is ".concat(answer)); -` - ); +`); }); - -test('adds helpers', async (t) => { +test('adds helpers', async () => { const code = await generate('class/main.js'); - t.true(code.includes('function _classCallCheck')); + expect(code.includes('function _classCallCheck')).toBe(true); }); - -test('adds helpers in loose mode', async (t) => { +test('adds helpers in loose mode', async () => { const code = await generate('class-loose/main.js'); - t.true(code.includes('function _inherits')); + expect(code.includes('function _inherits')).toBe(true); }); - -test('does not babelify excluded code', async (t) => { - const code = await generate('exclusions/main.js', { exclude: '**/foo.js' }); +test('does not babelify excluded code', async () => { + const code = await generate('exclusions/main.js', { + exclude: '**/foo.js' + }); // eslint-disable-next-line no-template-curly-in-string - t.false(code.includes('${foo()}')); - t.true(code.includes('=> 42')); - t.is( - code, - `'use strict'; + expect(code.includes('${foo()}')).toBe(false); + expect(code.includes('=> 42')).toBe(true); + expect(code).toBe(`'use strict'; const foo = () => 42; console.log("the answer is ".concat(foo())); -` - ); +`); }); - -test('does not babelify excluded code with custom filter', async (t) => { +test('does not babelify excluded code with custom filter', async () => { const filter = createFilter([], '**/foo.js'); - const code = await generate('exclusions/main.js', { filter }); + const code = await generate('exclusions/main.js', { + filter + }); // eslint-disable-next-line no-template-curly-in-string - t.false(code.includes('${foo()}')); - t.true(code.includes('=> 42')); - t.is( - code, - `'use strict'; + expect(code.includes('${foo()}')).toBe(false); + expect(code.includes('=> 42')).toBe(true); + expect(code).toBe(`'use strict'; const foo = () => 42; console.log("the answer is ".concat(foo())); -` - ); +`); }); - -test('does not babelify excluded code with code-based filter', async (t) => { +test('does not babelify excluded code with code-based filter', async () => { const filter = (id, code) => code.includes('the answer is'); - const code = await generate('exclusions/main.js', { filter }); + const code = await generate('exclusions/main.js', { + filter + }); // eslint-disable-next-line no-template-curly-in-string - t.false(code.includes('${foo()}')); - t.true(code.includes('=> 42')); - t.is( - code, - `'use strict'; + expect(code.includes('${foo()}')).toBe(false); + expect(code.includes('=> 42')).toBe(true); + expect(code).toBe(`'use strict'; const foo = () => 42; console.log("the answer is ".concat(foo())); -` - ); +`); }); - -test('does babelify included code with custom filter', async (t) => { +test('does babelify included code with custom filter', async () => { const filter = createFilter('**/foo.js', [], { resolve: DIRNAME }); - const code = await generate('exclusions/main.js', { filter }); + const code = await generate('exclusions/main.js', { + filter + }); // eslint-disable-next-line no-template-curly-in-string - t.true(code.includes('${foo()}')); - t.false(code.includes('=> 42')); - t.is( - code, - `'use strict'; + expect(code.includes('${foo()}')).toBe(true); + expect(code.includes('=> 42')).toBe(false); + expect(code).toBe(`'use strict'; var foo = function foo() { return 42; }; console.log(\`the answer is \${foo()}\`); -` - ); +`); }); - -test('does babelify excluded code with code-based filter', async (t) => { +test('does babelify excluded code with code-based filter', async () => { const filter = (id, code) => !code.includes('the answer is'); - const code = await generate('exclusions/main.js', { filter }); + const code = await generate('exclusions/main.js', { + filter + }); // eslint-disable-next-line no-template-curly-in-string - t.true(code.includes('${foo()}')); - t.false(code.includes('=> 42')); - t.is( - code, - `'use strict'; + expect(code.includes('${foo()}')).toBe(true); + expect(code.includes('=> 42')).toBe(false); + expect(code).toBe(`'use strict'; var foo = function foo() { return 42; }; console.log(\`the answer is \${foo()}\`); -` - ); +`); }); - -test('can not pass include or exclude when custom filter specified', async (t) => { +test('can not pass include or exclude when custom filter specified', async () => { const filter = createFilter('**/foo.js', [], { resolve: DIRNAME }); let errorWithExclude = ''; try { - await generate('exclusions/main.js', { filter, exclude: [] }); + await generate('exclusions/main.js', { + filter, + exclude: [] + }); } catch (e) { errorWithExclude = e.message; } - t.true(!!errorWithExclude); - + expect(!!errorWithExclude).toBe(true); let errorWithInclude = ''; try { - await generate('exclusions/main.js', { filter, include: [] }); + await generate('exclusions/main.js', { + filter, + include: [] + }); } catch (e) { errorWithInclude = e.message; } - t.true(!!errorWithInclude); + expect(!!errorWithInclude).toBe(true); }); - -test('generates sourcemap by default', async (t) => { +test('generates sourcemap by default', async () => { const bundle = await rollup({ input: `${FIXTURES}class/main.js`, - plugins: [babelPlugin({ babelHelpers: 'bundled' })] + plugins: [ + babelPlugin({ + babelHelpers: 'bundled' + }) + ] }); - const { output: [{ code, map }] - } = await bundle.generate({ format: 'cjs', exports: 'auto', sourcemap: true }); - + } = await bundle.generate({ + format: 'cjs', + exports: 'auto', + sourcemap: true + }); const target = 'log'; // source-map uses the presence of fetch to detect browser environments which @@ -219,39 +210,46 @@ test('generates sourcemap by default', async (t) => { const { SourceMapConsumer } = await import('source-map'); const smc = await new SourceMapConsumer(map); global.fetch = fetch; - const loc = getLocation(code, code.indexOf(target)); const original = smc.originalPositionFor(loc); - - t.deepEqual(original, { + expect(original).toEqual({ source: 'test/fixtures/class/main.js'.split(nodePath.sep).join('/'), line: 3, column: 12, name: target }); }); - -test('works with proposal-decorators (rollup/rollup-plugin-babel#18)', async (t) => { - await t.notThrowsAsync(() => +test('works with proposal-decorators (rollup/rollup-plugin-babel#18)', async () => { + await expect( rollup({ input: `${FIXTURES}proposal-decorators/main.js`, - plugins: [babelPlugin({ babelHelpers: 'bundled' })] + plugins: [ + babelPlugin({ + babelHelpers: 'bundled' + }) + ] }) - ); + ).resolves.toBeDefined(); }); - -test('checks config per-file', async (t) => { - const code = await generate('checks/main.js', {}, { format: 'es' }); - t.true(code.includes('class Foo')); - t.true(code.includes('var Bar')); - t.false(code.includes('class Bar')); +test('checks config per-file', async () => { + const code = await generate( + 'checks/main.js', + {}, + { + format: 'es' + } + ); + expect(code.includes('class Foo')).toBe(true); + expect(code.includes('var Bar')).toBe(true); + expect(code.includes('class Bar')).toBe(false); }); - -test('allows transform-runtime to be used instead of bundled helpers', async (t) => { +test('allows transform-runtime to be used instead of bundled helpers', async () => { const warnings = []; const code = await generate( 'runtime-helpers/main.js', - { babelHelpers: 'runtime' }, + { + babelHelpers: 'runtime' + }, {}, { onwarn(warning) { @@ -259,13 +257,11 @@ test('allows transform-runtime to be used instead of bundled helpers', async (t) } } ); - t.deepEqual(warnings, [ + expect(warnings).toEqual([ `"@babel/runtime/helpers/createClass" is imported by "test/fixtures/runtime-helpers/main.js", but could not be resolved – treating it as an external dependency.`, `"@babel/runtime/helpers/classCallCheck" is imported by "test/fixtures/runtime-helpers/main.js", but could not be resolved – treating it as an external dependency.` ]); - t.is( - code, - `'use strict'; + expect(code).toBe(`'use strict'; var _createClass = require('@babel/runtime/helpers/createClass'); var _classCallCheck = require('@babel/runtime/helpers/classCallCheck'); @@ -275,15 +271,15 @@ var Foo = /*#__PURE__*/_createClass(function Foo() { }); module.exports = Foo; -` - ); +`); }); - -test('allows transform-runtime to inject esm version of helpers', async (t) => { +test('allows transform-runtime to inject esm version of helpers', async () => { const warnings = []; const code = await generate( 'runtime-helpers-esm/main.js', - { babelHelpers: 'runtime' }, + { + babelHelpers: 'runtime' + }, { format: 'es' }, @@ -293,13 +289,11 @@ test('allows transform-runtime to inject esm version of helpers', async (t) => { } } ); - t.deepEqual(warnings, [ + expect(warnings).toEqual([ `"@babel/runtime/helpers/esm/createClass" is imported by "test/fixtures/runtime-helpers-esm/main.js", but could not be resolved – treating it as an external dependency.`, `"@babel/runtime/helpers/esm/classCallCheck" is imported by "test/fixtures/runtime-helpers-esm/main.js", but could not be resolved – treating it as an external dependency.` ]); - t.is( - code, - `import _createClass from '@babel/runtime/helpers/esm/createClass'; + expect(code).toBe(`import _createClass from '@babel/runtime/helpers/esm/createClass'; import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck'; var Foo = /*#__PURE__*/_createClass(function Foo() { @@ -307,28 +301,22 @@ var Foo = /*#__PURE__*/_createClass(function Foo() { }); export { Foo as default }; -` - ); +`); }); - -test('allows transform-runtime to be used instead of bundled helpers, but throws when CommonJS is used', async (t) => { - await t.throwsAsync( - () => generate('runtime-helpers-commonjs/main.js', { babelHelpers: 'runtime' }), - { - message: /Rollup requires that your Babel configuration keeps ES6 module syntax intact/ - } - ); +test('allows transform-runtime to be used instead of bundled helpers, but throws when CommonJS is used', async () => { + await expect( + generate('runtime-helpers-commonjs/main.js', { + babelHelpers: 'runtime' + }) + ).rejects.toThrow(/Rollup requires that your Babel configuration keeps ES6 module syntax intact/); }); - -test('allows using external-helpers plugin in combination with @babel/plugin-external-helpers', async (t) => { +test('allows using external-helpers plugin in combination with @babel/plugin-external-helpers', async () => { const code = await generate('external-helpers/main.js', { babelHelpers: 'external' }); - t.false(code.includes('function _classCallCheck')); - t.true(code.includes('babelHelpers.classCallCheck')); - t.is( - code, - `'use strict'; + expect(code.includes('function _classCallCheck')).toBe(false); + expect(code.includes('babelHelpers.classCallCheck')).toBe(true); + expect(code).toBe(`'use strict'; var Foo = /*#__PURE__*/babelHelpers.createClass(function Foo() { babelHelpers.classCallCheck(this, Foo); @@ -341,71 +329,74 @@ var Bar = /*#__PURE__*/babelHelpers.createClass(function Bar() { var main = [new Foo(), new Bar()]; module.exports = main; -` - ); +`); }); - -test('correctly renames helpers (rollup/rollup-plugin-babel#22)', async (t) => { +test('correctly renames helpers (rollup/rollup-plugin-babel#22)', async () => { const code = await generate('named-function-helper/main.js'); - t.false(code.includes('babelHelpers_get get'), 'helper was incorrectly renamed'); + expect(code.includes('babelHelpers_get get')).toBe(false); }); - -test('runs preflight check correctly in absence of class transformer (rollup/rollup-plugin-babel#23)', async (t) => { - await t.notThrowsAsync(() => +test('runs preflight check correctly in absence of class transformer (rollup/rollup-plugin-babel#23)', async () => { + await expect( rollup({ input: `${FIXTURES}no-class-transformer/main.js`, - plugins: [babelPlugin({ babelHelpers: 'bundled' })] + plugins: [ + babelPlugin({ + babelHelpers: 'bundled' + }) + ] }) - ); + ).resolves.toBeDefined(); }); - -test('produces valid code with typeof helper', async (t) => { +test('produces valid code with typeof helper', async () => { const code = await generate('typeof/main.js'); - t.false(code.includes('var typeof')); + expect(code.includes('var typeof')).toBe(false); }); - -test('handles babelrc with ignore option used', async (t) => { +test('handles babelrc with ignore option used', async () => { const code = await generate('ignored-file/main.js'); - t.true(code.includes('class Ignored')); + expect(code.includes('class Ignored')).toBe(true); }); - -test('transpiles only files with default extensions', async (t) => { +test('transpiles only files with default extensions', async () => { const code = await generate( 'extensions-default/main.js', {}, {}, { - plugins: [babelPlugin({ babelHelpers: 'bundled' }), jsonPlugin()] + plugins: [ + babelPlugin({ + babelHelpers: 'bundled' + }), + jsonPlugin() + ] } ); - t.false(code.includes('class Es '), 'should transpile .es'); - t.false(code.includes('class Es6 '), 'should transpile .es6'); - t.false(code.includes('class Js '), 'should transpile .js'); - t.false(code.includes('class Jsx '), 'should transpile .jsx'); - t.false(code.includes('class Mjs '), 'should transpile .mjs'); - t.true(code.includes('class Other '), 'should not transpile .other'); -}); - -test('transpiles only files with whitelisted extensions', async (t) => { + expect(code.includes('class Es ')).toBe(false); + expect(code.includes('class Es6 ')).toBe(false); + expect(code.includes('class Js ')).toBe(false); + expect(code.includes('class Jsx ')).toBe(false); + expect(code.includes('class Mjs ')).toBe(false); + expect(code.includes('class Other ')).toBe(true); +}); +test('transpiles only files with whitelisted extensions', async () => { const code = await generate('extensions-custom/main.js', { extensions: ['.js', '.other'] }); - t.true(code.includes('class Es '), 'should not transpile .es'); - t.true(code.includes('class Es6 '), 'should not transpile .es6'); - t.false(code.includes('class Js '), 'should transpile .js'); - t.true(code.includes('class Jsx '), 'should not transpile .jsx'); - t.true(code.includes('class Mjs '), 'should not transpile .mjs'); - t.false(code.includes('class Other '), 'should transpile .other'); -}); - -test('transpiles files when path contains query and hash', async (t) => { + expect(code.includes('class Es ')).toBe(true); + expect(code.includes('class Es6 ')).toBe(true); + expect(code.includes('class Js ')).toBe(false); + expect(code.includes('class Jsx ')).toBe(true); + expect(code.includes('class Mjs ')).toBe(true); + expect(code.includes('class Other ')).toBe(false); +}); +test('transpiles files when path contains query and hash', async () => { const code = await generate( 'with-query-and-hash/main.js', {}, {}, { plugins: [ - babelPlugin({ babelHelpers: 'bundled' }), + babelPlugin({ + babelHelpers: 'bundled' + }), // node-resolve plugin know how to resolve relative request with query nodeResolvePlugin(), { @@ -419,46 +410,38 @@ test('transpiles files when path contains query and hash', async (t) => { ] } ); - t.true(code.includes('function WithQuery()'), 'should transpile when path contains query'); - t.true(code.includes('function WithHash()'), 'should transpile when path contains hash'); - t.true( - code.includes('function WithQueryAndHash()'), - 'should transpile when path contains query and hash' - ); + expect(code.includes('function WithQuery()')).toBe(true); + expect(code.includes('function WithHash()')).toBe(true); + expect(code.includes('function WithQueryAndHash()')).toBe(true); }); - -test('throws when trying to add babel helper unavailable in used @babel/core version', async (t) => { - await t.throwsAsync( - () => - generate('basic/main.js', { - plugins: [ - function testPlugin() { - return { - visitor: { - Program(path, state) { - state.file.addHelper('__nonexistentHelper'); - } +test('throws when trying to add babel helper unavailable in used @babel/core version', async () => { + await expect( + generate('basic/main.js', { + plugins: [ + function testPlugin() { + return { + visitor: { + Program(path, state) { + state.file.addHelper('__nonexistentHelper'); } - }; - } - ] - }), - { - message: `${nodePath.resolve( - DIRNAME, - 'fixtures', - 'basic', - 'main.js' - )}: Unknown helper __nonexistentHelper` - } + } + }; + } + ] + }) + ).rejects.toThrow( + `${nodePath.resolve( + DIRNAME, + 'fixtures', + 'basic', + 'main.js' + )}: Unknown helper __nonexistentHelper` ); }); - -test('works with minified bundled helpers', async (t) => { +test('works with minified bundled helpers', async () => { const BASE_CHAR_CODE = 'a'.charCodeAt(0); let counter = 0; - - await t.notThrowsAsync(() => + await expect( generate('class/main.js', { plugins: [ function testPlugin({ types }) { @@ -469,7 +452,6 @@ test('works with minified bundled helpers', async (t) => { path .get('id') .replaceWith(types.identifier(String.fromCharCode(BASE_CHAR_CODE + counter))); - counter += 1; } } @@ -477,37 +459,35 @@ test('works with minified bundled helpers', async (t) => { } ] }) - ); + ).resolves.toBeDefined(); }); - -test('supports customizing the loader', async (t) => { +test('supports customizing the loader', async () => { const expectedRollupContextKeys = ['getCombinedSourcemap', 'getModuleIds', 'emitFile', 'resolve']; const customBabelPlugin = createBabelInputPluginFactory(() => { return { config(cfg) { - t.true(typeof this === 'object', 'override config this context is rollup context'); + expect(typeof this === 'object').toBe(true); expectedRollupContextKeys.forEach((key) => { - t.true( - Object.keys(this).includes(key), - `override config this context is rollup context with key ${key}` - ); + expect(Object.keys(this).includes(key)).toBe(true); }); return { ...cfg.options, plugins: [ ...(cfg.options.plugins || []), // Include a custom plugin in the options. - [replaceConsoleLogProperty, { replace: 'foobaz' }] + [ + replaceConsoleLogProperty, + { + replace: 'foobaz' + } + ] ] }; }, result(result) { - t.true(typeof this === 'object', 'override result this context is rollup context'); + expect(typeof this === 'object').toBe(true); expectedRollupContextKeys.forEach((key) => { - t.true( - Object.keys(this).includes(key), - `override result this context is rollup context with key ${key}` - ); + expect(Object.keys(this).includes(key)).toBe(true); }); return { ...result, @@ -518,20 +498,27 @@ test('supports customizing the loader', async (t) => { }); const bundle = await rollup({ input: `${FIXTURES}basic/main.js`, - plugins: [customBabelPlugin({ babelHelpers: 'bundled' })] + plugins: [ + customBabelPlugin({ + babelHelpers: 'bundled' + }) + ] }); const code = await getCode(bundle); - - t.true(code.includes('// Generated by some custom loader'), 'adds the custom comment'); - t.true(code.includes('console.foobaz'), 'runs the plugin'); + expect(code.includes('// Generated by some custom loader')).toBe(true); + expect(code.includes('console.foobaz')).toBe(true); }); - -test('supports overriding the plugin options in custom loader', async (t) => { +test('supports overriding the plugin options in custom loader', async () => { const customBabelPlugin = createBabelInputPluginFactory(() => { return { options(options) { // Ignore the js extension to test overriding the options - return { pluginOptions: { ...options, extensions: ['.x'] } }; + return { + pluginOptions: { + ...options, + extensions: ['.x'] + } + }; }, config(cfg) { return { @@ -539,7 +526,12 @@ test('supports overriding the plugin options in custom loader', async (t) => { plugins: [ ...(cfg.options.plugins || []), // Include a custom plugin in the options. - [replaceConsoleLogProperty, { replace: 'foobaz' }] + [ + replaceConsoleLogProperty, + { + replace: 'foobaz' + } + ] ] }; }, @@ -553,25 +545,30 @@ test('supports overriding the plugin options in custom loader', async (t) => { }); const bundle = await rollup({ input: `${FIXTURES}basic/main.js`, - plugins: [customBabelPlugin({ babelHelpers: 'bundled' })] + plugins: [ + customBabelPlugin({ + babelHelpers: 'bundled' + }) + ] }); const code = await getCode(bundle); - - t.false( - code.includes('// Generated by some custom loader'), - 'does not add the comment to ignored file' - ); - t.false(code.includes('console.foobaz'), 'does not run the plugin on ignored file'); + expect(code.includes('// Generated by some custom loader')).toBe(false); + expect(code.includes('console.foobaz')).toBe(false); }); - -test('uses babel plugins passed in to the rollup plugin', async (t) => { +test('uses babel plugins passed in to the rollup plugin', async () => { const code = await generate('basic/main.js', { - plugins: [[replaceConsoleLogProperty, { replace: 'foobaz' }]] + plugins: [ + [ + replaceConsoleLogProperty, + { + replace: 'foobaz' + } + ] + ] }); - t.true(code.includes('console.foobaz')); + expect(code.includes('console.foobaz')).toBe(true); }); - -test('can be used as an input plugin while transforming the output', async (t) => { +test('can be used as an input plugin while transforming the output', async () => { const bundle = await rollup({ input: `${FIXTURES}basic/main.js`, plugins: [ @@ -581,11 +578,9 @@ test('can be used as an input plugin while transforming the output', async (t) = ] }); const code = await getCode(bundle); - - t.false(code.includes('const')); + expect(code.includes('const')).toBe(false); }); - -test('works as a CJS plugin', async (t) => { +test('works as a CJS plugin', async () => { const require = createRequire(import.meta.url); const babelPluginCjs = require('current-package'); const bundle = await rollup({ @@ -597,6 +592,5 @@ test('works as a CJS plugin', async (t) => { ] }); const code = await getCode(bundle); - - t.false(code.includes('const')); + expect(code.includes('const')).toBe(false); }); diff --git a/packages/babel/test/as-output-plugin.mjs b/packages/babel/test/as-output-plugin.mjs index ca10af2a9..25b5c977a 100644 --- a/packages/babel/test/as-output-plugin.mjs +++ b/packages/babel/test/as-output-plugin.mjs @@ -1,8 +1,7 @@ import * as nodePath from 'path'; - import { fileURLToPath } from 'url'; -import test from 'ava'; +import { test, expect } from 'vitest'; import { rollup } from 'rollup'; import { getBabelOutputPlugin, createBabelOutputPluginFactory } from 'current-package'; @@ -11,28 +10,24 @@ import { getCode } from '../../../util/test.js'; const DIRNAME = fileURLToPath(new URL('.', import.meta.url)); const FIXTURES = `${DIRNAME}/fixtures/`; - function getLocation(source, charIndex) { const lines = source.split('\n'); const len = lines.length; - let lineStart = 0; - for (let i = 0; i < len; i += 1) { const line = lines[i]; // +1 for newline const lineEnd = lineStart + line.length + 1; - if (lineEnd > charIndex) { - return { line: i + 1, column: charIndex - lineStart }; + return { + line: i + 1, + column: charIndex - lineStart + }; } - lineStart = lineEnd; } - throw new Error('Could not determine location of character'); } - function replaceConsoleLogProperty({ types: t }) { return { name: 'replace-console-log-property', @@ -46,13 +41,11 @@ function replaceConsoleLogProperty({ types: t }) { } }; } - async function generate(input, babelOptions = {}, generateOptions = {}, rollupOptions = {}) { const bundle = await rollup({ input: FIXTURES + input, ...rollupOptions }); - return getCode(bundle, { format: 'cjs', exports: 'auto', @@ -60,31 +53,35 @@ async function generate(input, babelOptions = {}, generateOptions = {}, rollupOp ...generateOptions }); } - -test('allows running the plugin on the output via output options', async (t) => { +test('allows running the plugin on the output via output options', async () => { const code = await generate('basic/main.js', { presets: ['@babel/env'] }); - t.false(code.includes('const')); + expect(code.includes('const')).toBe(false); }); - -test('ignores .babelrc when transforming the output by default', async (t) => { +test('ignores .babelrc when transforming the output by default', async () => { const code = await generate('basic/main.js'); - t.true(code.includes('const')); + expect(code.includes('const')).toBe(true); }); - -test("allows transform-runtime to be used with `useESModules: false` (the default) and `format: 'cjs'`", async (t) => { +test("allows transform-runtime to be used with `useESModules: false` (the default) and `format: 'cjs'`", async () => { const code = await generate( 'runtime-helpers/main.js', { presets: ['@babel/env'], - plugins: [['@babel/transform-runtime', { useESModules: false }]] + plugins: [ + [ + '@babel/transform-runtime', + { + useESModules: false + } + ] + ] }, - { format: 'cjs' } + { + format: 'cjs' + } ); - t.is( - code, - `'use strict'; + expect(code).toBe(`'use strict'; var _createClass = require("@babel/runtime/helpers/createClass"); var _classCallCheck = require("@babel/runtime/helpers/classCallCheck"); @@ -92,34 +89,38 @@ var Foo = /*#__PURE__*/_createClass(function Foo() { _classCallCheck(this, Foo); }); module.exports = Foo; -` - ); +`); }); - -test("allows transform-runtime to be used with `useESModules: true` and `format: 'es'`", async (t) => { +test("allows transform-runtime to be used with `useESModules: true` and `format: 'es'`", async () => { const code = await generate( 'runtime-helpers/main.js', { presets: ['@babel/env'], - plugins: [['@babel/transform-runtime', { useESModules: true }]] + plugins: [ + [ + '@babel/transform-runtime', + { + useESModules: true + } + ] + ] }, - { format: 'es' } + { + format: 'es' + } ); - t.is( - code, - `import _createClass from "@babel/runtime/helpers/esm/createClass"; + expect(code).toBe(`import _createClass from "@babel/runtime/helpers/esm/createClass"; import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck"; var Foo = /*#__PURE__*/_createClass(function Foo() { _classCallCheck(this, Foo); }); export { Foo as default }; -` - ); +`); }); - -test('generates sourcemap by default', async (t) => { - const bundle = await rollup({ input: `${FIXTURES}class/main.js` }); - +test('generates sourcemap by default', async () => { + const bundle = await rollup({ + input: `${FIXTURES}class/main.js` + }); const { output: [{ code, map }] } = await bundle.generate({ @@ -128,7 +129,6 @@ test('generates sourcemap by default', async (t) => { plugins: [getBabelOutputPlugin()], sourcemap: true }); - const target = 'log'; // source-map uses the presence of fetch to detect browser environments which @@ -138,19 +138,16 @@ test('generates sourcemap by default', async (t) => { const { SourceMapConsumer } = await import('source-map'); const smc = await new SourceMapConsumer(map); global.fetch = fetch; - const loc = getLocation(code, code.indexOf(target)); const original = smc.originalPositionFor(loc); - - t.deepEqual(original, { + expect(original).toEqual({ source: 'test/fixtures/class/main.js'.split(nodePath.sep).join('/'), line: 3, column: 12, name: target }); }); - -test('allows using external-helpers plugin even if the externalHelpers flag is not passed', async (t) => { +test('allows using external-helpers plugin even if the externalHelpers flag is not passed', async () => { const warnings = []; const code = await generate( 'external-helpers/main.js', @@ -165,12 +162,10 @@ test('allows using external-helpers plugin even if the externalHelpers flag is n } } ); - t.deepEqual(warnings, []); - t.false(code.includes('function _classCallCheck')); - t.true(code.includes('babelHelpers.classCallCheck')); - t.is( - code, - `'use strict'; + expect(warnings).toEqual([]); + expect(code.includes('function _classCallCheck')).toBe(false); + expect(code.includes('babelHelpers.classCallCheck')).toBe(true); + expect(code).toBe(`'use strict'; var Foo = /*#__PURE__*/babelHelpers.createClass(function Foo() { babelHelpers.classCallCheck(this, Foo); @@ -180,11 +175,9 @@ var Bar = /*#__PURE__*/babelHelpers.createClass(function Bar() { }); var main = [new Foo(), new Bar()]; module.exports = main; -` - ); +`); }); - -test('warns when using the "include" option', async (t) => { +test('warns when using the "include" option', async () => { const warnings = []; await generate( 'basic/main.js', @@ -198,13 +191,14 @@ test('warns when using the "include" option', async (t) => { } } ); - t.deepEqual(warnings, [ + expect(warnings).toEqual([ 'The "include", "exclude" and "extensions" options are ignored when transforming the output.' ]); }); - -test('transforms all chunks in a code-splitting setup', async (t) => { - const bundle = await rollup({ input: `${FIXTURES}chunks/main.js` }); +test('transforms all chunks in a code-splitting setup', async () => { + const bundle = await rollup({ + input: `${FIXTURES}chunks/main.js` + }); const output = await getCode( bundle, { @@ -218,24 +212,19 @@ test('transforms all chunks in a code-splitting setup', async (t) => { }, true ); - - t.deepEqual( - output.map(({ code }) => code), - [ - `import('./dep--s88I99N.js').then(function (result) { + expect(output.map(({ code }) => code)).toEqual([ + `import('./dep--s88I99N.js').then(function (result) { return console.log(result); }); `, - `var dep = function dep() { + `var dep = function dep() { return 42; }; export { dep as default }; ` - ] - ); + ]); }); - -test('transforms all chunks when preserving modules', async (t) => { +test('transforms all chunks when preserving modules', async () => { const bundle = await rollup({ input: `${FIXTURES}preserve-modules/main.js` }); @@ -252,51 +241,44 @@ test('transforms all chunks when preserving modules', async (t) => { }, true ); - - t.deepEqual( - output.map(({ code }) => code), - [ - `import getResult from './dep.js'; + expect(output.map(({ code }) => code)).toEqual([ + `import getResult from './dep.js'; var value = 42; console.log(getResult(value)); `, - `var getResult = function getResult(value) { + `var getResult = function getResult(value) { return value + 1; }; export { getResult as default }; ` - ] - ); + ]); }); - -test('supports customizing the loader', async (t) => { +test('supports customizing the loader', async () => { const expectedRollupContextKeys = ['getModuleIds', 'emitFile', 'resolve', 'parse']; const customBabelPlugin = createBabelOutputPluginFactory(() => { return { config(cfg) { - t.true(typeof this === 'object', 'override config this context is rollup context'); + expect(typeof this === 'object').toBe(true); expectedRollupContextKeys.forEach((key) => { - t.true( - Object.keys(this).includes(key), - `override config this context is rollup context with key ${key}` - ); + expect(Object.keys(this).includes(key)).toBe(true); }); return Object.assign({}, cfg.options, { plugins: [ ...(cfg.options.plugins || []), - // Include a custom plugin in the options. - [replaceConsoleLogProperty, { replace: 'foobaz' }] + [ + replaceConsoleLogProperty, + { + replace: 'foobaz' + } + ] ] }); }, result(result) { - t.true(typeof this === 'object', 'override result this context is rollup context'); + expect(typeof this === 'object').toBe(true); expectedRollupContextKeys.forEach((key) => { - t.true( - Object.keys(this).includes(key), - `override result this context is rollup context with key ${key}` - ); + expect(Object.keys(this).includes(key)).toBe(true); }); return Object.assign({}, result, { code: `${result.code}\n// Generated by some custom loader` @@ -304,46 +286,66 @@ test('supports customizing the loader', async (t) => { } }; }); - const bundle = await rollup({ input: `${FIXTURES}basic/main.js` }); - const code = await getCode(bundle, { format: 'cjs', plugins: [customBabelPlugin()] }); - - t.true(code.includes('// Generated by some custom loader'), 'adds the custom comment'); - t.true(code.includes('console.foobaz'), 'runs the plugin'); -}); - -test('throws when using a Rollup output format other than esm or cjs', async (t) => { - await t.throwsAsync(() => generate('basic/main.js', {}, { format: 'iife' }), { - message: `Using Babel on the generated chunks is strongly discouraged for formats other than "esm" or "cjs" as it can easily break wrapper code and lead to accidentally created global variables. Instead, you should set "output.format" to "esm" and use Babel to transform to another format, e.g. by adding "presets: [['@babel/env', { modules: 'umd' }]]" to your Babel options. If you still want to proceed, add "allowAllFormats: true" to your plugin options.` + const bundle = await rollup({ + input: `${FIXTURES}basic/main.js` + }); + const code = await getCode(bundle, { + format: 'cjs', + plugins: [customBabelPlugin()] }); + expect(code.includes('// Generated by some custom loader')).toBe(true); + expect(code.includes('console.foobaz')).toBe(true); }); - -test('allows using a Rollup output format other than esm or cjs with allowAllFormats', async (t) => { +test('throws when using a Rollup output format other than esm or cjs', async () => { + await expect( + generate( + 'basic/main.js', + {}, + { + format: 'iife' + } + ) + ).rejects.toThrow( + `Using Babel on the generated chunks is strongly discouraged for formats other than "esm" or "cjs" as it can easily break wrapper code and lead to accidentally created global variables. Instead, you should set "output.format" to "esm" and use Babel to transform to another format, e.g. by adding "presets: [['@babel/env', { modules: 'umd' }]]" to your Babel options. If you still want to proceed, add "allowAllFormats: true" to your plugin options.` + ); +}); +test('allows using a Rollup output format other than esm or cjs with allowAllFormats', async () => { const code = await generate( 'basic/main.js', - { presets: ['@babel/env'], allowAllFormats: true }, - { format: 'iife' } + { + presets: ['@babel/env'], + allowAllFormats: true + }, + { + format: 'iife' + } ); - t.is( - code, - `(function () { + expect(code).toBe(`(function () { 'use strict'; var answer = 42; console.log("the answer is ".concat(answer)); })(); -` - ); +`); }); - -test('allows using Babel to transform to other formats', async (t) => { +test('allows using Babel to transform to other formats', async () => { const code = await generate( 'basic/main.js', - { presets: [['@babel/env', { modules: 'umd' }]] }, - { format: 'es' } + { + presets: [ + [ + '@babel/env', + { + modules: 'umd' + } + ] + ] + }, + { + format: 'es' + } ); - t.is( - code, - `(function (global, factory) { + expect(code).toBe(`(function (global, factory) { if (typeof define === "function" && define.amd) { define([], factory); } else if (typeof exports !== "undefined") { @@ -361,29 +363,22 @@ test('allows using Babel to transform to other formats', async (t) => { var answer = 42; console.log("the answer is ".concat(answer)); }); -` - ); +`); }); - -test('loads configuration files when configFile is passed', async (t) => { +test('loads configuration files when configFile is passed', async () => { const code = await generate('config-file/main.js', { configFile: nodePath.resolve(DIRNAME, 'fixtures/config-file/config.json') }); - t.is( - code, - `'use strict'; + expect(code).toBe(`'use strict'; const answer = Math.pow(42, 2); console.log(\`the answer is \${answer}\`); -` - ); +`); }); - -test('allows excluding manual chunks from output transform via `excludeChunks`', async (t) => { +test('allows excluding manual chunks from output transform via `excludeChunks`', async () => { const bundle = await rollup({ input: `${FIXTURES}chunks/main.js` }); - const output = await getCode( bundle, { @@ -403,9 +398,8 @@ test('allows excluding manual chunks from output transform via `excludeChunks`', }, true ); - const codes = output.map(({ code }) => code); // The vendor chunk should remain untransformed and contain the arrow function as-is // Debug output intentionally omitted - t.true(codes.some((c) => c.includes('=> 42'))); + expect(codes.some((c) => c.includes('=> 42'))).toBe(true); }); diff --git a/packages/dynamic-import-vars/package.json b/packages/dynamic-import-vars/package.json index 2bcacff7b..778de9c31 100644 --- a/packages/dynamic-import-vars/package.json +++ b/packages/dynamic-import-vars/package.json @@ -28,13 +28,13 @@ "ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov", "ci:lint": "pnpm build && pnpm lint", "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}", - "ci:test": "pnpm test -- --verbose", + "ci:test": "pnpm test -- --reporter=verbose", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", "prerelease": "pnpm build", "pretest": "pnpm build --sourcemap", "release": "pnpm --workspace-root package:release $(pwd)", - "test": "ava" + "test": "vitest --config ../../.config/vitest.config.mts run" }, "files": [ "dist", @@ -75,12 +75,5 @@ "prettier": "^2.7.1", "rollup": "^4.0.0-24" }, - "types": "./types/index.d.ts", - "ava": { - "workerThreads": false, - "files": [ - "!**/fixtures/**", - "!**/snapshots/**" - ] - } + "types": "./types/index.d.ts" } diff --git a/packages/dynamic-import-vars/test/rollup-plugin-dynamic-import-vars.test.js b/packages/dynamic-import-vars/test/rollup-plugin-dynamic-import-vars.test.js index 58c40091c..63e1144c1 100644 --- a/packages/dynamic-import-vars/test/rollup-plugin-dynamic-import-vars.test.js +++ b/packages/dynamic-import-vars/test/rollup-plugin-dynamic-import-vars.test.js @@ -2,38 +2,35 @@ const { join } = require('path'); -const test = require('ava'); const { rollup } = require('rollup'); const dynamicImportVars = require('current-package'); process.chdir(join(__dirname, 'fixtures')); - -test('single dir', async (t) => { +test('single dir', async () => { const bundle = await rollup({ input: 'fixture-single-dir.js', plugins: [dynamicImportVars()] }); - const { output } = await bundle.generate({ format: 'es' }); + const { output } = await bundle.generate({ + format: 'es' + }); const expectedFiles = [ require.resolve('./fixtures/fixture-single-dir.js'), require.resolve('./fixtures/module-dir-a/module-a-1.js'), require.resolve('./fixtures/module-dir-a/module-a-2.js') ]; - - t.deepEqual( - expectedFiles, - output.map((o) => o.facadeModuleId) - ); - t.snapshot(output[0].code); + expect(expectedFiles).toEqual(output.map((o) => o.facadeModuleId)); + expect(output[0].code).toMatchSnapshot(); }); - -test('multiple dirs', async (t) => { +test('multiple dirs', async () => { const bundle = await rollup({ input: 'fixture-multiple-dirs.js', plugins: [dynamicImportVars()] }); - const { output } = await bundle.generate({ format: 'es' }); + const { output } = await bundle.generate({ + format: 'es' + }); const expectedFiles = [ require.resolve('./fixtures/fixture-multiple-dirs.js'), require.resolve('./fixtures/module-dir-a/module-a-1.js'), @@ -42,39 +39,33 @@ test('multiple dirs', async (t) => { require.resolve('./fixtures/module-dir-b/module-b-2.js'), require.resolve('./fixtures/sub-dir/fixture-upwards-path.js') ]; - - t.deepEqual( - expectedFiles, - output.map((o) => o.facadeModuleId) - ); - t.snapshot(output[0].code); + expect(expectedFiles).toEqual(output.map((o) => o.facadeModuleId)); + expect(output[0].code).toMatchSnapshot(); }); - -test('upwards dir path', async (t) => { +test('upwards dir path', async () => { const bundle = await rollup({ input: 'sub-dir/fixture-upwards-path', plugins: [dynamicImportVars()] }); - const { output } = await bundle.generate({ format: 'es' }); + const { output } = await bundle.generate({ + format: 'es' + }); const expectedFiles = [ require.resolve('./fixtures/sub-dir/fixture-upwards-path.js'), require.resolve('./fixtures/module-dir-a/module-a-1.js'), require.resolve('./fixtures/module-dir-a/module-a-2.js') ]; - - t.deepEqual( - expectedFiles, - output.map((o) => o.facadeModuleId) - ); - t.snapshot(output[0].code); + expect(expectedFiles).toEqual(output.map((o) => o.facadeModuleId)); + expect(output[0].code).toMatchSnapshot(); }); - -test('complex concatenation', async (t) => { +test('complex concatenation', async () => { const bundle = await rollup({ input: 'fixture-complex-concat.js', plugins: [dynamicImportVars()] }); - const { output } = await bundle.generate({ format: 'es' }); + const { output } = await bundle.generate({ + format: 'es' + }); const expectedFiles = [ require.resolve('./fixtures/fixture-complex-concat.js'), require.resolve('./fixtures/module-dir-a/module-a-1.js'), @@ -82,39 +73,33 @@ test('complex concatenation', async (t) => { require.resolve('./fixtures/module-dir-b/module-b-1.js'), require.resolve('./fixtures/module-dir-b/module-b-2.js') ]; - - t.deepEqual( - expectedFiles, - output.map((o) => o.facadeModuleId) - ); - t.snapshot(output[0].code); + expect(expectedFiles).toEqual(output.map((o) => o.facadeModuleId)); + expect(output[0].code).toMatchSnapshot(); }); - -test('own directory', async (t) => { +test('own directory', async () => { const bundle = await rollup({ input: 'fixture-own-dir.js', plugins: [dynamicImportVars()] }); - const { output } = await bundle.generate({ format: 'es' }); + const { output } = await bundle.generate({ + format: 'es' + }); const expectedFiles = [ require.resolve('./fixtures/fixture-own-dir.js'), require.resolve('./fixtures/root-module-a.js'), require.resolve('./fixtures/root-module-b.js') ]; - - t.deepEqual( - expectedFiles, - output.map((o) => o.facadeModuleId) - ); - t.snapshot(output[0].code); + expect(expectedFiles).toEqual(output.map((o) => o.facadeModuleId)); + expect(output[0].code).toMatchSnapshot(); }); - -test('multiple dynamic imports', async (t) => { +test('multiple dynamic imports', async () => { const bundle = await rollup({ input: 'fixture-multiple-imports.js', plugins: [dynamicImportVars()] }); - const { output } = await bundle.generate({ format: 'es' }); + const { output } = await bundle.generate({ + format: 'es' + }); const expectedFiles = [ require.resolve('./fixtures/fixture-multiple-imports.js'), require.resolve('./fixtures/module-dir-a/module-a-1.js'), @@ -123,33 +108,25 @@ test('multiple dynamic imports', async (t) => { require.resolve('./fixtures/module-dir-b/module-b-2.js'), require.resolve('./fixtures/sub-dir/fixture-upwards-path.js') ]; - - t.deepEqual( - expectedFiles, - output.map((o) => o.facadeModuleId) - ); - t.snapshot(output[0].code); + expect(expectedFiles).toEqual(output.map((o) => o.facadeModuleId)); + expect(output[0].code).toMatchSnapshot(); }); - -test("doesn't change imports that should not be changed", async (t) => { +test("doesn't change imports that should not be changed", async () => { const bundle = await rollup({ input: 'fixture-unchanged.js', plugins: [dynamicImportVars()] }); - const { output } = await bundle.generate({ format: 'es' }); + const { output } = await bundle.generate({ + format: 'es' + }); const expectedFiles = [ require.resolve('./fixtures/fixture-unchanged.js'), require.resolve('./fixtures/module-dir-a/module-a-2.js') ]; - - t.deepEqual( - expectedFiles, - output.map((o) => o.facadeModuleId) - ); - t.snapshot(output[0].code); + expect(expectedFiles).toEqual(output.map((o) => o.facadeModuleId)); + expect(output[0].code).toMatchSnapshot(); }); - -test('can exclude files', async (t) => { +test('can exclude files', async () => { const bundle = await rollup({ input: 'fixture-excluded.js', plugins: [ @@ -158,18 +135,14 @@ test('can exclude files', async (t) => { }) ] }); - const { output } = await bundle.generate({ format: 'es' }); - + const { output } = await bundle.generate({ + format: 'es' + }); const expectedFiles = [require.resolve('./fixtures/fixture-excluded.js')]; - - t.deepEqual( - expectedFiles, - output.map((o) => o.facadeModuleId) - ); - t.snapshot(output[0].code); + expect(expectedFiles).toEqual(output.map((o) => o.facadeModuleId)); + expect(output[0].code).toMatchSnapshot(); }); - -test('throws an error on failure', async (t) => { +test('throws an error on failure', async () => { let thrown; try { await rollup({ @@ -183,29 +156,25 @@ test('throws an error on failure', async (t) => { } catch (_) { thrown = true; } - t.is(thrown, true); + expect(thrown).toBe(true); }); - -test('dynamic imports assertions', async (t) => { +test('dynamic imports assertions', async () => { const bundle = await rollup({ input: 'fixture-assert.js', plugins: [dynamicImportVars()] }); - const { output } = await bundle.generate({ format: 'es' }); + const { output } = await bundle.generate({ + format: 'es' + }); const expectedFiles = [ require.resolve('./fixtures/fixture-assert.js'), require.resolve('./fixtures/module-dir-a/module-a-1.js'), require.resolve('./fixtures/module-dir-a/module-a-2.js') ]; - - t.deepEqual( - expectedFiles, - output.map((o) => o.facadeModuleId) - ); - t.snapshot(output[0].code); + expect(expectedFiles).toEqual(output.map((o) => o.facadeModuleId)); + expect(output[0].code).toMatchSnapshot(); }); - -test("doesn't throw if no files in dir when option isn't set", async (t) => { +test("doesn't throw if no files in dir when option isn't set", async () => { let thrown = false; try { await rollup({ @@ -215,36 +184,41 @@ test("doesn't throw if no files in dir when option isn't set", async (t) => { } catch (_) { thrown = true; } - t.false(thrown); + expect(thrown).toBe(false); }); - -test('throws if no files in dir when `errorWhenNoFilesFound` is set', async (t) => { +test('throws if no files in dir when `errorWhenNoFilesFound` is set', async () => { let thrown = false; try { await rollup({ input: 'fixture-no-files.js', - plugins: [dynamicImportVars({ errorWhenNoFilesFound: true })] + plugins: [ + dynamicImportVars({ + errorWhenNoFilesFound: true + }) + ] }); } catch (error) { - t.deepEqual( - error.message, + expect(error.message).toEqual( `No files found in ./module-dir-c/*.js when trying to dynamically load concatted string from ${require.resolve( './fixtures/fixture-no-files.js' )}` ); thrown = true; } - t.true(thrown); + expect(thrown).toBe(true); }); - -test('warns if no files in dir when `errorWhenNoFilesFound` and `warnOnError` are both set', async (t) => { +test('warns if no files in dir when `errorWhenNoFilesFound` and `warnOnError` are both set', async () => { let warningEmitted = false; await rollup({ input: 'fixture-no-files.js', - plugins: [dynamicImportVars({ errorWhenNoFilesFound: true, warnOnError: true })], + plugins: [ + dynamicImportVars({ + errorWhenNoFilesFound: true, + warnOnError: true + }) + ], onwarn(warning) { - t.deepEqual( - warning.message, + expect(warning.message).toEqual( `No files found in ./module-dir-c/*.js when trying to dynamically load concatted string from ${require.resolve( './fixtures/fixture-no-files.js' )}` @@ -252,5 +226,5 @@ test('warns if no files in dir when `errorWhenNoFilesFound` and `warnOnError` ar warningEmitted = true; } }); - t.true(warningEmitted); + expect(warningEmitted).toBe(true); }); diff --git a/packages/dynamic-import-vars/test/snapshots/rollup-plugin-dynamic-import-vars.test.js.snap b/packages/dynamic-import-vars/test/snapshots/rollup-plugin-dynamic-import-vars.test.js.snap index 8ee67b5d83ef2e95272bfbecccf13a9140b5b0e2..c82ca964e0cfb7dcfcc5835e5e9ab97951f0d5b0 100644 GIT binary patch literal 7062 zcmeHMZExa65dO}u7)6zAbQmA>TJ;jq>P}a#_aRl)dr_-W!P*{Rb7t4^t_d{azjxNy zU=xFrOH-W^BBaQ87|+f;^Y++v;S<-WG`trqQd6m6-f6*9>qwot?mWHM4sh;H5+0zd zGO6}d&%#Cn7mLkwZ+JjNsouwj9z+;EGgKw^l?5cgC2BYR#W0gM@u1gwWb=Ej(jL!1g#wa<9 zLR^3^h0in!mYQ+Xu;FmdV$Qq}-z@1_+<%u^`gDcfd;{P! zg<$R2ogIQX9kSdy-8tq~ngpCNPsIE0f9V@ZIwH{DVV&JNon7Y=qrhMOF+Z%+%bo4j z*+~Mr{{E?;SZB&@wUSYIs+WDB-9(93A}>eVmadq?Ho;Zj7o-c zY>{Ix(AVqe7|+>y8KE4*Wr7Kwb3c}vsn5{s^}x!1ZNX2w_fJ8g{y_1TiEi3y42-t5 z_O{1GV2dOSTVSmDIgVv)pL`Ubg}f4w!v}&jellR5!U;Ts6g$mKVHVw0dcA4@p*gpy zgl3z-|0}_s9=Dq)^=KW8C}~V0rT+@qMAw<#)nG&)vd(g?)jd)ykf?;E!JjfQ!R!bM z^pt6!YLbKj2&yR_W)i`+E>Kod1hE~;iEU99801$wcEDn@o3WKRun@+kO!E7p>Rie&C zJiZM7JWr0jxHPMhYrn7$r!AO%zPisCyUohdbaD3t?H(stT0NZqagseI=tB+5hZ|$( z(IEYaPDO{q`*>FJrxjj5q)i9;UprcmugmLb_TY-8 z)DRh@kGK>WFSl#@hMqX=#M`H2ETwj`O`GkRPD?UQ*#C~dcz#huj}-;ITPX9KerL(W z%a_L)x5QH1X3c0M5RitJ8Kdwxyy?9=K6o4T^64P>tcZU@6s rXzzi;Y;iVqFy(C@4vi1;wqT#q8XBI6&8pW0M?8KhA-5BUI|K4xg|Qol literal 1006 zcmVsFvLoV@lpjH>f|nf>N}XJ-Ai=`!K%sW0D9 zQ_ZlgDBooWK9y8)5~!BY>ho9MCz^a*>Mk!_UWh)6mlm!rxl7HEdzuOk_4+=Ml(-C^ z_BrWL?`0I*Qa5wJ6#NXufMaO!t}98LZ<)h<9GnC zrRY$F_ShJD>}SN^znv}rpwjcssnq*G#q>CSH)@xtmL0vQ^^HVj+C3475F7-TrXaC0RI%TC8w zod%=8RL3K8d60=rwtV3tGY8WhFWhNz8Up8b*Z)L5+<87T<`g*%fm6S~8}y!6X%40e z-3V~4Nqc5LI$>}?q_3RF_7i~fNS(H9cG<`6ut?HOk{Z(*R;S9;)q&YOJb8`=iC>}= zjit^hAUcz#IQIhbU-GmlA!nk5{A&#fJ<%~0qz9hh9?{52Bv?)@*~kRx&7zi^)ml=d zQhdqFQ$ldlCOV{^y;~Z^uoR8x`n-1?)4Z^3Ti^c8cZm;bGxsLxEiL@ zPl~_6RCEiuZIAvh!PdiAMl+fjmtcj7UE3PzfxcCSgv?ZY^UH58YR0=ysXW!q$NG#n zAI8GvJf`V>qv{J(+|uB+2;aqVw*k6EG?;cHWIk}A!Nr8aKh}us{L1tpKNm7)FqZ&1<@S<05II`QUCw| diff --git a/packages/dynamic-import-vars/test/src/dynamic-import-to-glob.test.mjs b/packages/dynamic-import-vars/test/src/dynamic-import-to-glob.test.mjs index 17f50124c..5061efc20 100644 --- a/packages/dynamic-import-vars/test/src/dynamic-import-to-glob.test.mjs +++ b/packages/dynamic-import-vars/test/src/dynamic-import-to-glob.test.mjs @@ -1,288 +1,235 @@ /* eslint-disable import/extensions, import/no-unresolved, no-template-curly-in-string */ import { parse } from 'acorn'; -import test from 'ava'; +import { test, expect } from 'vitest'; import { dynamicImportToGlob, VariableDynamicImportError } from 'current-package'; -test('template literal with variable filename', (t) => { +test('template literal with variable filename', () => { const ast = parse('import(`./foo/${bar}.js`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './foo/*.js'); + expect(glob).toBe('./foo/*.js'); }); - -test('external', (t) => { +test('external', () => { const ast = parse('import(`https://some.cdn.com/package/${version}/index.js`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, null); + expect(glob).toBe(null); }); - -test('external - leaves bare module specifiers starting with https in tact', (t) => { +test('external - leaves bare module specifiers starting with https in tact', () => { const ast = parse('import("http_utils");', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, null); + expect(glob).toBe(null); }); - -test('data uri', (t) => { +test('data uri', () => { const ast = parse('import(`data:${bar}`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, null); + expect(glob).toBe(null); }); - -test('template literal with dot-prefixed suffix', (t) => { +test('template literal with dot-prefixed suffix', () => { const ast = parse('import(`./${bar}.entry.js`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './*.entry.js'); + expect(glob).toBe('./*.entry.js'); }); - -test('template literal with variable directory', (t) => { +test('template literal with variable directory', () => { const ast = parse('import(`./foo/${bar}/x.js`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './foo/*/x.js'); + expect(glob).toBe('./foo/*/x.js'); }); - -test('template literal with multiple variables', (t) => { +test('template literal with multiple variables', () => { const ast = parse('import(`./${foo}/${bar}.js`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './*/*.js'); + expect(glob).toBe('./*/*.js'); }); - -test('dynamic expression with variable filename', (t) => { +test('dynamic expression with variable filename', () => { const ast = parse('import("./foo/".concat(bar,".js"));', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './foo/*.js'); + expect(glob).toBe('./foo/*.js'); }); - -test('dynamic expression with variable directory', (t) => { +test('dynamic expression with variable directory', () => { const ast = parse('import("./foo/".concat(bar, "/x.js"));', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './foo/*/x.js'); + expect(glob).toBe('./foo/*/x.js'); }); - -test('dynamic expression with multiple variables', (t) => { +test('dynamic expression with multiple variables', () => { const ast = parse('import("./".concat(foo, "/").concat(bar,".js"));', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './*/*.js'); + expect(glob).toBe('./*/*.js'); }); - -test('string concatenation', (t) => { +test('string concatenation', () => { const ast = parse('import("./foo/" + bar + ".js");', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './foo/*.js'); + expect(glob).toBe('./foo/*.js'); }); - -test('string concatenation and template literals combined', (t) => { +test('string concatenation and template literals combined', () => { const ast = parse('import("./" + `foo/${bar}` + ".js");', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './foo/*.js'); + expect(glob).toBe('./foo/*.js'); }); - -test('string literal in a template literal expression', (t) => { +test('string literal in a template literal expression', () => { const ast = parse('import(`${"./foo/"}${bar}.js`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './foo/*.js'); + expect(glob).toBe('./foo/*.js'); }); - -test('multiple variables are collapsed into a single *', (t) => { +test('multiple variables are collapsed into a single *', () => { const ast = parse('import(`./foo/${bar}${baz}/${x}${y}.js`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './foo/*/*.js'); + expect(glob).toBe('./foo/*/*.js'); }); - -test('throws when dynamic import contains a *', (t) => { +test('throws when dynamic import contains a *', () => { const ast = parse('import(`./*${foo}.js`);', { sourceType: 'module' }); - let error; try { dynamicImportToGlob(ast.body[0].expression.source); } catch (e) { error = e; } - t.is(error.message, 'A dynamic import cannot contain * characters.'); - t.true(error instanceof VariableDynamicImportError); + expect(error.message).toBe('A dynamic import cannot contain * characters.'); + expect(error instanceof VariableDynamicImportError).toBe(true); }); - -test('throws when dynamic import contains a non + operator', (t) => { +test('throws when dynamic import contains a non + operator', () => { const ast = parse('import("foo" - "bar.js");', { sourceType: 'module' }); - let error; try { dynamicImportToGlob(ast.body[0].expression.source); } catch (e) { error = e; } - t.is(error.message, '- operator is not supported.'); - t.true(error instanceof VariableDynamicImportError); + expect(error.message).toBe('- operator is not supported.'); + expect(error instanceof VariableDynamicImportError).toBe(true); }); - -test('throws when dynamic import is a single variable', (t) => { +test('throws when dynamic import is a single variable', () => { const ast = parse('import(foo);', { sourceType: 'module' }); - let error; try { dynamicImportToGlob(ast.body[0].expression.source, '${sourceString}'); } catch (e) { error = e; } - t.is( - error.message, + expect(error.message).toBe( 'invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. For example: import(`./foo/${bar}.js`).' ); - t.true(error instanceof VariableDynamicImportError); + expect(error instanceof VariableDynamicImportError).toBe(true); }); - -test('throws when dynamic import starts with a variable', (t) => { +test('throws when dynamic import starts with a variable', () => { const ast = parse('import(`${folder}/foo.js`);', { sourceType: 'module' }); - let error; try { dynamicImportToGlob(ast.body[0].expression.source, '${sourceString}'); } catch (e) { error = e; } - t.is( - error.message, + expect(error.message).toBe( 'invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. For example: import(`./foo/${bar}.js`).' ); - t.true(error instanceof VariableDynamicImportError); + expect(error instanceof VariableDynamicImportError).toBe(true); }); - -test('throws when dynamic import starts with a /', (t) => { +test('throws when dynamic import starts with a /', () => { const ast = parse('import(`/foo/${bar}.js`);', { sourceType: 'module' }); - let error; try { dynamicImportToGlob(ast.body[0].expression.source, '${sourceString}'); } catch (e) { error = e; } - t.is( - error.message, + expect(error.message).toBe( 'invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. For example: import(`./foo/${bar}.js`).' ); - t.true(error instanceof VariableDynamicImportError); + expect(error instanceof VariableDynamicImportError).toBe(true); }); - -test('throws when dynamic import does not start with ./', (t) => { +test('throws when dynamic import does not start with ./', () => { const ast = parse('import(`foo/${bar}.js`);', { sourceType: 'module' }); - let error; try { dynamicImportToGlob(ast.body[0].expression.source, '${sourceString}'); } catch (e) { error = e; } - t.is( - error.message, + expect(error.message).toBe( 'invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. For example: import(`./foo/${bar}.js`).' ); - t.true(error instanceof VariableDynamicImportError); + expect(error instanceof VariableDynamicImportError).toBe(true); }); - -test("throws when dynamic import imports it's own directory", (t) => { +test("throws when dynamic import imports it's own directory", () => { const ast = parse('import(`./${foo}.js`);', { sourceType: 'module' }); - let error; try { dynamicImportToGlob(ast.body[0].expression.source, '${sourceString}'); } catch (e) { error = e; } - t.is( - error.message, + expect(error.message).toBe( 'invalid import "${sourceString}". Variable imports cannot import their own directory, place imports in a separate directory or make the import filename more specific. For example: import(`./foo/${bar}.js`).' ); - t.true(error instanceof VariableDynamicImportError); + expect(error instanceof VariableDynamicImportError).toBe(true); }); - -test('throws when dynamic import imports does not contain a file extension', (t) => { +test('throws when dynamic import imports does not contain a file extension', () => { const ast = parse('import(`./foo/${bar}`);', { sourceType: 'module' }); - let error; try { dynamicImportToGlob(ast.body[0].expression.source, '${sourceString}'); } catch (e) { error = e; } - t.is( - error.message, + expect(error.message).toBe( 'invalid import "${sourceString}". A file extension must be included in the static part of the import. For example: import(`./foo/${bar}.js`).' ); - t.true(error instanceof VariableDynamicImportError); + expect(error instanceof VariableDynamicImportError).toBe(true); }); - -test('escapes ()', (t) => { +test('escapes ()', () => { const ast = parse('import(`./${foo}/(foo).js`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './*/\\(foo\\).js'); + expect(glob).toBe('./*/\\(foo\\).js'); }); - -test('escapes []', (t) => { +test('escapes []', () => { const ast = parse('import(`./${foo}/[foo].js`);', { sourceType: 'module' }); - const glob = dynamicImportToGlob(ast.body[0].expression.source); - t.is(glob, './*/\\[foo\\].js'); + expect(glob).toBe('./*/\\[foo\\].js'); }); diff --git a/packages/esm-shim/package.json b/packages/esm-shim/package.json index d7d84887e..c5ca37a8d 100644 --- a/packages/esm-shim/package.json +++ b/packages/esm-shim/package.json @@ -28,13 +28,13 @@ "ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov", "ci:lint": "pnpm build && pnpm lint", "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}", - "ci:test": "pnpm test -- --verbose && pnpm test:ts", + "ci:test": "pnpm test -- --reporter=verbose && pnpm test:ts", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", "prerelease": "pnpm build", "pretest": "pnpm build", "release": "pnpm --workspace-root package:release $(pwd)", - "test": "ava", + "test": "vitest --config ../../.config/vitest.config.mts run", "test:ts": "tsc types/index.d.ts test/types.ts --noEmit" }, "files": [ diff --git a/packages/esm-shim/test/snapshots/test.js.snap b/packages/esm-shim/test/snapshots/test.js.snap index 56705e6526167abd66b98c8ee729fa301541e67e..0c457ad6f3253288f33d38968d0c5a976f0cfa15 100644 GIT binary patch literal 2525 zcmeHJOK;mS48HqU5Zl2SkjUsYMUT5RK+&wbtV68YN~~6|>5;4`_TNWYYV2+qQUp5& z2;i8cM4BJTk5vUeN?O}T{h0c59=2f-rb);q6Y7=ca> zm2TNQSW#Y%)Hl?3W4*!mHwFvc2EoQAvX`JyqZNMOYPIHqDJmI;k{psKxx2moqT}_G z6bzBfQ-c0K4JTV}hlA0UWXWW>b#HFjkHBsAlENa5Wz@6Vr1__#rsJZ;=<*GdvKN$i zbIvrpK(hIDiMg!z^5Y2XIOdOn<7$Ih%4v5VgOW^*0Lq#L-SB4VEt=<)$|#w+UW7R< z&PXE0ry!ZC(IL!=?O>GXNqGS2DL6O{Y#D^-<^b4kXvd5;R#j{fsysRyw@_oBjn_k; zjiNo5MH(ajtHF=POiX`T1r)0petsrr~gU$v7Qs!z49Bg`C^`#5PaVI3Czl z^$}8r7t|P>tjIi9NJIpGnDb);9mzQ$J1C^+2V|2c&Y~v%#=C(h!7dY~|I`q%H9Q+0hHfSgS literal 624 zcmV-$0+0PcRzVeb*j_lGLS_ zt2sbZKOc(-00000000B+Rm*PEKom_t2+2Es0A0btK}wu`tFS{XAfjrB1ZBVCv z&uMBQJvU%hOu#~EphkdlHg}d8NpiDN)_l3iGGfX5?uYxGhaLaxKIlBU_o^EWhcFnx z1cMFUL`>vL7YV1D!$KvsWm`$ADY5jl z^xRq~T``_vT*%Oi3qy?lh+Y(fUIoncakM36a5pKiVYoS?oKC4Ac?(CM8yu|<9Q`|v zhQp^}^<$FfOfGSd5mrp_LNaz7K9R~o8;}0smY3_@w9Z@iW$X+EV>L@H?sMO6O|pd) z|COvp`^bub!J&}Sz_GEoK|y8PQShT7vv1uHGA2uwPOxpc48joJGBAb7Pjb-XU+S?0 z7<5XysV}-0x9GKx$l9^;d>{UWeoa5btYlsY)gkJd~^NbPUi Kl@5Xy3IG7 { +test.sequential('inject cjs shim for esm output', async () => { const bundle = await rollup({ input: 'test/fixtures/cjs.js', plugins: [esmShim()] }); - const result = await bundle.generate({ format: 'es' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'es' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.snapshot(output.code); - t.falsy(output.map); + expect(output.code).toMatchSnapshot(); + expect(output.map).toBeFalsy(); }); - -test.serial('inject cjs shim for esm output with sourcemap', async (t) => { +test.sequential('inject cjs shim for esm output with sourcemap', async () => { const bundle = await rollup({ input: 'test/fixtures/cjs.js', plugins: [esmShim()] }); - const result = await bundle.generate({ format: 'es', sourcemap: true }); - t.is(result.output.length, 2); + const result = await bundle.generate({ + format: 'es', + sourcemap: true + }); + expect(result.output.length).toBe(2); const [output, map] = result.output; - t.snapshot(output.code); - t.truthy(output.map); - t.is(output.map.file, 'cjs.js'); - t.deepEqual(output.map.sources, ['test/fixtures/cjs.js']); - t.is(map.fileName, 'cjs.js.map'); + expect(output.code).toMatchSnapshot(); + expect(output.map).toBeTruthy(); + expect(output.map.file).toBe('cjs.js'); + expect(output.map.sources).toEqual(['test/fixtures/cjs.js']); + expect(map.fileName).toBe('cjs.js.map'); }); - -test.serial('not inject cjs shim for cjs output', async (t) => { +test.sequential('not inject cjs shim for cjs output', async () => { const bundle = await rollup({ input: 'test/fixtures/cjs.js', plugins: [esmShim()] }); - const result = await bundle.generate({ format: 'cjs' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'cjs' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.snapshot(output.code); - t.falsy(output.map); + expect(output.code).toMatchSnapshot(); + expect(output.map).toBeFalsy(); }); - -test.serial('inject cjs shim for esm output with a single import statement', async (t) => { +test.sequential('inject cjs shim for esm output with a single import statement', async () => { const bundle = await rollup({ input: 'test/fixtures/cjs-single-import.js', plugins: [esmShim()], external: ['magic-string'] }); - const result = await bundle.generate({ format: 'es' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'es' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.snapshot(output.code); - t.falsy(output.map); + expect(output.code).toMatchSnapshot(); + expect(output.map).toBeFalsy(); }); - -test.serial('inject cjs shim for esm output with multiple import statements', async (t) => { +test.sequential('inject cjs shim for esm output with multiple import statements', async () => { const bundle = await rollup({ input: 'test/fixtures/cjs-multiple-imports.js', plugins: [esmShim()], external: ['magic-string', 'node:crypto'] }); - const result = await bundle.generate({ format: 'es' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'es' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.snapshot(output.code); - t.falsy(output.map); + expect(output.code).toMatchSnapshot(); + expect(output.map).toBeFalsy(); }); // see issue #1649 https://github.com/rollup/plugins/issues/1649 -test.serial( +test.sequential( 'inject cjs shim should not break on valid js object with `import` literal value', - async (t) => { + async () => { const bundle = await rollup({ input: 'test/fixtures/cjs-import-literal.js', plugins: [esmShim()] }); - const result = await bundle.generate({ format: 'es' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'es' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.snapshot(output.code); - t.falsy(output.map); + expect(output.code).toMatchSnapshot(); + expect(output.map).toBeFalsy(); } ); diff --git a/packages/html/package.json b/packages/html/package.json index 9e1966e70..b80bde9c2 100644 --- a/packages/html/package.json +++ b/packages/html/package.json @@ -28,13 +28,13 @@ "ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov", "ci:lint": "pnpm build && pnpm lint", "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}", - "ci:test": "pnpm test -- --verbose", + "ci:test": "pnpm test -- --reporter=verbose", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", "prerelease": "pnpm build", "pretest": "pnpm build", "release": "pnpm --workspace-root package:release $(pwd)", - "test": "ava", + "test": "vitest --config ../../.config/vitest.config.mts run", "test:ts": "tsc --noEmit" }, "files": [ @@ -66,14 +66,5 @@ "rollup-plugin-postcss": "^4.0.2", "typescript": "^4.8.3" }, - "types": "./types/index.d.ts", - "ava": { - "workerThreads": false, - "files": [ - "!**/fixtures/**", - "!**/helpers/**", - "!**/recipes/**", - "!**/types.ts" - ] - } + "types": "./types/index.d.ts" } diff --git a/packages/html/test/snapshots/test.js.snap b/packages/html/test/snapshots/test.js.snap index a7bf303220881770d96b4b64cec6b2aeb6dd1d64..bc9d7c124a6b3eb241683fcfa0b7aa84d80a6e30 100644 GIT binary patch literal 7606 zcmeHMYj4{&6#X3iiaPiJTzDr6ljB@X*UdQ5Hk{Gv!O^$B%K;V{`)RP z$(CKmd2dN!1GYu+lDyJ=9UcY&{J}I;8jb|X)KF>|bv9tAb*A=$U{v(AV>${3hQ%~c zrBr*UQ|@{6YbJB8KJ|&#IXg8t6Lk8=5JKPk5S)8mZF1Y(*nK_Lu7XjFm?c=oL9Xp=OCU(3dH{GPW~&edFh;a#jZYm4CQ&@hUE zLhT~mc;VsaVjboD4X0VcI6Wk3q1_jGM)UR;RrRGLL#2h`ycAZ_#3G0_Cqwy)KFcD9^ewzXZm?rd#e($V>4+R@qEtv5Dn zjm}TC#^%nnvHN^_U0-phHt$YNrhdKs^K|TPO};))XKO~MYQS-I;ag9!j#s`QvsHKbJgU_GQYVw@3C3OX%r`Ig9l$M23(>v{f`_X^nlNBQlyLG_DIi?Z6W3*;0Lrl;sEv z1xPvCjndOiT`O|3U=g6RA}47%)^jU%o$leRxn! zR#PG4X23+tBCb97Fr;&S+K7-;0;T|ID~MT6BhAM!@#;3bgvcl@Q~2Dk($MF=9grb< zCZ{Nz)4vT4jN5QD2?iGh3Sm^lO-%QIstx?62&`~-ya6VSD_xy}_Oxq)3abN`e*yV~ BJ~99R literal 1673 zcmV;426p*DRzVCuDFx~UN$@!awl%Z`B!raRVhKplQV7rx z)TF$fdE0$u{;V@^fR%uX9{dvxH#IRa;6=F@FL*JL_=f{`6XOXZHxC{>8BLVgnO*3z zWhv0oO7}8v-n{SIZ{PfWzi+;8_Ix34d*-p=y$eD~Wed*|1s>Xpc_k%1H;{qLOF_|7 z!5il-iz|La`zM7~L?3FS)CK@s06Ytzo0hDgmSNxLWuoe+tE&s7gEUYF(F?I*2ho}6 zNRf}0uK;`vV4Q$=2>6T=UrYAoCxxjGi7^89iyJEga)a!GgvW{HAy1~+WPedP z_H-fK=H%88T2^S6pl6@7JTux~7C9Qyv(bUs+?~i7!Zn6;#!&;if3!xGyOx|S`n1My^KLF8$m>MEP}ta4%)n7%A27Wih)sO_pT zlpTmKRF)6K>$3xuC=;4YOiPc{*gT_0rv_ve=`n}&=tv^CAAT&O2g8qe+U1VO8ONnK zQSy9cFw=9Da8=H5q${1!=?hG5i`>TbOuAA@Zr_|ZAuUzRS>m`fMPKD)D(iM|W%A?q z#<$3DU`D*Nq%4RAIq9R>BHiBr))KJ2Iq6;|AWy()0zN0;yLywEk&ZG`>7cha;6u-X zAjD$6Fh$@rfbHwE1>2th{0m@JbJ%VnAWOhu0?rcf$$i3>9t}YLFpmMrqM&ky<5{6C z?gpMGSA}j6mZIb!Earu(6e?Eme21%>s6AUn?FX}k+TQ?l5|C+*+MNVEPka z6SZA+;<||81%u%SE2gj3V43~`z?T4i2C%v*B-5J+*h+v&!0P%3?(}VNOx+2NOLy(v zf9S~gj%2EyG%GGRc2-}bdL?PWIv65&@!SS4X7Hm zM300)^FWsE9~s-dXLS7V@PW}iqr2}MiuNH&b~qv3zUambvO`5NRZLjMoD4Ed2F&#o zv!pLfWtUk^divQgGs8f64m+xZQ?j`dN2BE>-^=s7U1q*`C6s=&@?cG`V&4Iiu4#vs z7-S+?&qUy?XVKH*dKNlXJrCkAYri-qQ5$Kd21soxWK#8zA<)vuTWvF!#M@lW^=8nZ zE=(W21)k~600sf<1hB6eL{k-DzF33k`w2ulh%QG%t)hs30{9ES`5Vf3m4NHbMU*t4 zRRatS7}0=2lQOZ5TFz*|TN?1G23*yE>-8or|KG~8ZPGg?{D&y{?QsBRFl_{pk7Y!E zq;4`jiD5qEo8RX$-(+p+9%Dsc6mmvw-wfspJ7)x{Y>S{Mgo?khXBju zNdsHcz)-qMlO189Ap9sF=ws4VTVtj#?*cu6mDK$-I~AAQgKXo54Qsct(|YC3QQgk! z`LYrt!ktjX%2b-V6Zx6sO8GJ$D$z)V-dt3nMHQMO6d)?^$=8vMQrUmE^W!(WZ{gJ$`S?P=M3eCcOg{6Y2c+az~@e=CZrQRz%}Zjx6Nh` z{cQp+G?%4s3HXtKYXo#?z}iQshu-FUdAY!g+wbRHaa-Ngd+5(RZk1i`NOL^l%(&~R zaogjTuo}?k+#DtOg9N-rz{kzmbcuj(2>9hL-$+F*o*T*ic?}R6a83g*Hm|Ag*y72_ z0_)k!Rk7dauH`vBy=*Pp6j6||cw2ii{mJWyz7v}_Oo-v<4)#w5nTS|TDbrzcb;6s? zme5`GR#)C0{{rUlm3hbETki7AXRNq>+`c~b#0m?^bmSgGq3a- readFileSync(join('output/', file), 'utf-8'); -const output = { dir: 'output', format: 'umd' }; - +const output = { + dir: 'output', + format: 'umd' +}; process.chdir(join(__dirname, 'fixtures')); - -test.serial('default options', async (t) => { +test.sequential('default options', async () => { const bundle = await rollup({ input: 'batman.js', plugins: [html()] }); const code = await getCode(bundle, output, true); - t.snapshot(code); + expect(code).toMatchSnapshot(); }); - -test.serial('options', async (t) => { +test.sequential('options', async () => { const bundle = await rollup({ input: 'batman.js', plugins: [ @@ -32,92 +30,131 @@ test.serial('options', async (t) => { publicPath: 'batcave/', title: 'Batcave', meta: [ - { charset: 'utf-8' }, - { name: 'viewport', content: 'minimum-scale=1, initial-scale=1, width=device-width' } + { + charset: 'utf-8' + }, + { + name: 'viewport', + content: 'minimum-scale=1, initial-scale=1, width=device-width' + } ] }) ] }); const code = await getCode(bundle, output, true); - t.snapshot(code); + expect(code).toMatchSnapshot(); }); - -test.serial('iife', async (t) => { +test.sequential('iife', async () => { const bundle = await rollup({ input: 'batman.js', plugins: [html()] }); - const code = await getCode(bundle, { dir: 'output', format: 'iife' }, true); - t.snapshot(code); + const code = await getCode( + bundle, + { + dir: 'output', + format: 'iife' + }, + true + ); + expect(code).toMatchSnapshot(); }); - -test.serial('esm', async (t) => { +test.sequential('esm', async () => { const bundle = await rollup({ input: 'batman.js', plugins: [html()] }); - const code = await getCode(bundle, { dir: 'output', format: 'es' }, true); - t.snapshot(code); + const code = await getCode( + bundle, + { + dir: 'output', + format: 'es' + }, + true + ); + expect(code).toMatchSnapshot(); }); - -test.serial('unsupported output format', async (t) => { +test.sequential('unsupported output format', async () => { const warnings = []; const bundle = await rollup({ input: 'batman.js', onwarn: (warning) => warnings.push(warning), plugins: [html()] }); - const code = await getCode(bundle, { dir: 'output', format: 'cjs' }, true); - t.snapshot(code); - t.snapshot(warnings); + const code = await getCode( + bundle, + { + dir: 'output', + format: 'cjs' + }, + true + ); + expect(code).toMatchSnapshot(); + expect(warnings).toMatchSnapshot(); }); - -test.serial('css', async (t) => { +test.sequential('css', async () => { const bundle = await rollup({ input: 'joker.js', - plugins: [css({ extract: true }), html()] + plugins: [ + css({ + extract: true + }), + html() + ] }); const code = await getCode(bundle, output, true); - t.snapshot(code); + expect(code).toMatchSnapshot(); }); - -test.serial('attributes', async (t) => { +test.sequential('attributes', async () => { const bundle = await rollup({ input: 'joker.js', plugins: [ - css({ extract: true }), + css({ + extract: true + }), html({ attributes: { - html: { batsignal: 'on', lang: 'bat' }, - link: { 'data-vilian': 'joker' }, - script: { defer: true } + html: { + batsignal: 'on', + lang: 'bat' + }, + link: { + 'data-vilian': 'joker' + }, + script: { + defer: true + } } }) ] }); const code = await getCode(bundle, output, true); - t.snapshot(code); + expect(code).toMatchSnapshot(); }); - -test.serial('imports', async (t) => { +test.sequential('imports', async () => { const bundle = await rollup({ input: 'robin.js', plugins: [html()] }); const code = await getCode(bundle, output, true); - t.snapshot(code); + expect(code).toMatchSnapshot(); }); - -test.serial('dynamic_imports_not_loaded', async (t) => { +test.sequential('dynamic_imports_not_loaded', async () => { const bundle = await rollup({ input: 'catwoman.js', plugins: [html()] }); - const code = await getCode(bundle, { dir: 'output', format: 'esm' }, true); - t.snapshot(code); + const code = await getCode( + bundle, + { + dir: 'output', + format: 'esm' + }, + true + ); + expect(code).toMatchSnapshot(); }); - -test.serial('template', async (t) => { +test.sequential('template', async () => { const bundle = await rollup({ input: 'batman.js', plugins: [ @@ -127,22 +164,25 @@ test.serial('template', async (t) => { ] }); const code = await getCode(bundle, output, true); - t.snapshot(code); + expect(code).toMatchSnapshot(); }); - -test.serial('scripts on head', async (t) => { +test.sequential('scripts on head', async () => { const bundle = await rollup({ input: 'joker.js', plugins: [ - css({ extract: true }), + css({ + extract: true + }), html({ attributes: { - script: { defer: true } + script: { + defer: true + } }, addScriptsToHead: true }) ] }); const code = await getCode(bundle, output, true); - t.snapshot(code); + expect(code).toMatchSnapshot(); }); diff --git a/packages/json/package.json b/packages/json/package.json index c6a48c83c..41576afcf 100755 --- a/packages/json/package.json +++ b/packages/json/package.json @@ -28,13 +28,13 @@ "ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov", "ci:lint": "pnpm build && pnpm lint", "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}", - "ci:test": "pnpm test -- --verbose && pnpm test:ts", + "ci:test": "pnpm test -- --reporter=verbose && pnpm test:ts", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", "prerelease": "pnpm build", "pretest": "pnpm build", "release": "pnpm --workspace-root package:release $(pwd)", - "test": "ava", + "test": "vitest --config ../../.config/vitest.config.mts run", "test:ts": "tsc types/index.d.ts test/types.ts --noEmit" }, "files": [ @@ -70,14 +70,5 @@ "rollup": "^4.0.0-24", "source-map-support": "^0.5.21" }, - "types": "./types/index.d.ts", - "ava": { - "workerThreads": false, - "files": [ - "!**/fixtures/**", - "!**/helpers/**", - "!**/recipes/**", - "!**/types.ts" - ] - } + "types": "./types/index.d.ts" } diff --git a/packages/json/test/snapshots/test.js.snap b/packages/json/test/snapshots/test.js.snap index 6762a647c768c3ac91d7bacb5d232eb8491ba881..0f81e165252cebc87a8c5d24bb5b2c3d74796fdd 100644 GIT binary patch literal 1417 zcmdT^!H%0S5Iy6s82L;Wu}4Ros-AkR)Jqg8E*=uJU?bb48%6o|j(P1mq2=I?#>1)1;pqL~L{Xe3>_y?JIE<~r!X?(r(f1u=_&ylx-FAOK zjaE`2sExH)ds-F3@75n_*AKGxmA4~8x!*wrdmi6}leBbot@@7ViLki=G@T1ob#db_ zf(18k{CbN^YvsAxmN|dryBSc}$g%U6xvH2qIdAo}|MG@sF3LQX7jem_Vq&`Iycu=v zTcf$)nk*R|DxPyab{!Yte%=1KWl_Ncx^qpC)BZZUz)E~GQVg=O<;1q8ctmaR_> zB|S<95A-Z~1Hl}YT?vgsU`t>iXJih`cA?T=Rd6GVfG7;Y!blo>TH9c;LHpHc3Q+3o zBC4LA&U&cnLC_{ehC&hEiAo3~DJvz{JK`jYc%&+b3YvBc<)8M=9}etQ<5w1@<}a?r z{y*;(duY~R&49K$Lt|_&Jq09i0Ms0cXqAn0Mb?lU^5-H_Un0zQCL8Xz0c0g1` zVP4vs{l+=j-aA<;mBN&2C%DMz%phWh>PQMrUAR9E-18hRwdu8V&FClan&5xW_ss;1 zT%}2lAr~A4fhLuUVHfPx0eks}od)o!tp@gA0oG{&tl~2Hju*g3FaTG~%vwWcM%I|^ zZ`yLH9G5Jm#4>aVA05JnRfP4-xZ{^hTRJN@i$A(0C;guB8pN*FbRo5Xa+UhMR;UGP zbQ+u`nI)K3#a?IeoaAs5iC|;oKkM((NyZAj0_NU readFileSync(file, 'utf-8'); - require('source-map-support').install(); process.chdir(__dirname); - -test('converts json', async (t) => { +test('converts json', async () => { const bundle = await rollup({ input: 'fixtures/basic/main.js', plugins: [json()] }); - t.plan(1); - return testBundle(t, bundle); + expect.assertions(1); + return testBundle(avaAssertions, bundle); }); - -test('handles arrays', async (t) => { +test('handles arrays', async () => { const bundle = await rollup({ input: 'fixtures/array/main.js', plugins: [json()] }); - t.plan(1); - return testBundle(t, bundle); + expect.assertions(1); + return testBundle(avaAssertions, bundle); }); - -test('handles literals', async (t) => { +test('handles literals', async () => { const bundle = await rollup({ input: 'fixtures/literal/main.js', plugins: [json()] }); - t.plan(1); - return testBundle(t, bundle); + expect.assertions(1); + return testBundle(avaAssertions, bundle); }); - -test('generates named exports', async (t) => { +test('generates named exports', async () => { const bundle = await rollup({ input: 'fixtures/named/main.js', plugins: [json()] }); - - const { code, result } = await testBundle(t, bundle, { inject: { exports: {} } }); - - t.is(result.version, '1.33.7'); - t.is(code.indexOf('this-should-be-excluded'), -1, 'should exclude unused properties'); + const { code, result } = await testBundle(avaAssertions, bundle, { + inject: { + exports: {} + } + }); + expect(result.version).toBe('1.33.7'); + expect(code.indexOf('this-should-be-excluded')).toBe(-1); }); - -test('generates named exports including arbitrary names', async (t) => { +test('generates named exports including arbitrary names', async () => { const bundle = await rollup({ input: 'fixtures/arbitrary/main.js', - plugins: [json({ includeArbitraryNames: true })] + plugins: [ + json({ + includeArbitraryNames: true + }) + ] }); - - const { result } = await testBundle(t, bundle, { inject: { exports: {} } }); - - t.is(result.bar, 'baz'); + const { result } = await testBundle(avaAssertions, bundle, { + inject: { + exports: {} + } + }); + expect(result.bar).toBe('baz'); }); - -test('resolves extensionless imports in conjunction with the node-resolve plugin', async (t) => { +test('resolves extensionless imports in conjunction with the node-resolve plugin', async () => { const bundle = await rollup({ input: 'fixtures/extensionless/main.js', - plugins: [nodeResolve({ extensions: ['.js', '.json'] }), json()] + plugins: [ + nodeResolve({ + extensions: ['.js', '.json'] + }), + json() + ] }); - t.plan(2); - return testBundle(t, bundle); + expect.assertions(2); + return testBundle(avaAssertions, bundle); }); - -test('handles JSON objects with no valid keys (#19)', async (t) => { +test('handles JSON objects with no valid keys (#19)', async () => { const bundle = await rollup({ input: 'fixtures/no-valid-keys/main.js', plugins: [json()] }); - t.plan(1); - return testBundle(t, bundle); -}); - -test('handles garbage', async (t) => { - const err = await t.throwsAsync( - rollup({ - input: 'fixtures/garbage/main.js', - plugins: [json()] - }) - ); - t.is(err.code, 'PLUGIN_ERROR'); - t.is(err.plugin, 'json'); - t.is(err.message, 'Could not parse JSON file'); - t.is(err.name, 'RollupError'); - t.is(err.cause.name, 'SyntaxError'); - t.regex(err.id, /(.*)bad.json$/); + expect.assertions(1); + return testBundle(avaAssertions, bundle); }); - -test('does not generate an AST', async (t) => { +test('handles garbage', async () => { + const err = await rollup({ + input: 'fixtures/garbage/main.js', + plugins: [json()] + }).catch((error) => error); + expect(err.code).toBe('PLUGIN_ERROR'); + expect(err.plugin).toBe('json'); + expect(err.message).toBe('Could not parse JSON file'); + expect(err.name).toBe('RollupError'); + expect(err.cause.name).toBe('SyntaxError'); + expect(err.id).toMatch(/(.*)bad.json$/); +}); +test('does not generate an AST', async () => { // eslint-disable-next-line no-undefined - t.is(json().transform(read('fixtures/form/input.json'), 'input.json').ast, undefined); + expect(json().transform(read('fixtures/form/input.json'), 'input.json').ast).toBe(undefined); }); - -test('does not generate source maps', async (t) => { - t.deepEqual(json().transform(read('fixtures/form/input.json'), 'input.json').map, { +test('does not generate source maps', async () => { + expect(json().transform(read('fixtures/form/input.json'), 'input.json').map).toEqual({ mappings: '' }); }); - -test('generates properly formatted code', async (t) => { +test('generates properly formatted code', async () => { const { code } = json().transform(read('fixtures/form/input.json'), 'input.json'); - t.snapshot(code); -}); - -test('generates correct code with preferConst', async (t) => { - const { code } = json({ preferConst: true }).transform( - read('fixtures/form/input.json'), - 'input.json' - ); - t.snapshot(code); -}); - -test('uses custom indent string', async (t) => { - const { code } = json({ indent: ' ' }).transform(read('fixtures/form/input.json'), 'input.json'); - t.snapshot(code); -}); - -test('generates correct code with compact=true', async (t) => { - const { code } = json({ compact: true }).transform( - read('fixtures/form/input.json'), - 'input.json' - ); - t.snapshot(code); -}); - -test('generates correct code with namedExports=false', async (t) => { - const { code } = json({ namedExports: false }).transform( - read('fixtures/form/input.json'), - 'input.json' - ); - t.snapshot(code); -}); - -test('correctly formats arrays with compact=true', async (t) => { - t.deepEqual( - json({ compact: true }).transform( + expect(code).toMatchSnapshot(); +}); +test('generates correct code with preferConst', async () => { + const { code } = json({ + preferConst: true + }).transform(read('fixtures/form/input.json'), 'input.json'); + expect(code).toMatchSnapshot(); +}); +test('uses custom indent string', async () => { + const { code } = json({ + indent: ' ' + }).transform(read('fixtures/form/input.json'), 'input.json'); + expect(code).toMatchSnapshot(); +}); +test('generates correct code with compact=true', async () => { + const { code } = json({ + compact: true + }).transform(read('fixtures/form/input.json'), 'input.json'); + expect(code).toMatchSnapshot(); +}); +test('generates correct code with namedExports=false', async () => { + const { code } = json({ + namedExports: false + }).transform(read('fixtures/form/input.json'), 'input.json'); + expect(code).toMatchSnapshot(); +}); +test('correctly formats arrays with compact=true', async () => { + expect( + json({ + compact: true + }).transform( `[ 1, { @@ -153,14 +154,11 @@ test('correctly formats arrays with compact=true', async (t) => { } ]`, 'input.json' - ).code, - 'export default[1,{x:1}];' - ); + ).code + ).toEqual('export default[1,{x:1}];'); }); - -test('handles empty keys', async (t) => { - t.deepEqual( - json().transform(`{"":"a", "b": "c"}`, 'input.json').code, +test('handles empty keys', async () => { + expect(json().transform(`{"":"a", "b": "c"}`, 'input.json').code).toEqual( 'export var b = "c";\nexport default {\n\t"": "a",\n\tb: b\n};\n' ); }); diff --git a/packages/replace/package.json b/packages/replace/package.json index 798172bae..84fd2b5de 100644 --- a/packages/replace/package.json +++ b/packages/replace/package.json @@ -28,13 +28,13 @@ "ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov", "ci:lint": "pnpm build && pnpm lint", "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}", - "ci:test": "pnpm test -- --verbose && pnpm test:ts", + "ci:test": "pnpm test -- --reporter=verbose && pnpm test:ts", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", "prerelease": "pnpm build", "pretest": "pnpm build", "release": "pnpm --workspace-root package:release $(pwd)", - "test": "ava", + "test": "vitest --config ../../.config/vitest.config.mts run", "test:ts": "tsc types/index.d.ts test/types.ts --noEmit" }, "files": [ @@ -73,14 +73,5 @@ "source-map": "^0.7.4", "typescript": "^4.8.3" }, - "types": "./types/index.d.ts", - "ava": { - "workerThreads": false, - "files": [ - "!**/fixtures/**", - "!**/helpers/**", - "!**/recipes/**", - "!**/types.ts" - ] - } + "types": "./types/index.d.ts" } diff --git a/packages/replace/test/form.js b/packages/replace/test/form.js index 287a1d508..4fbf04805 100644 --- a/packages/replace/test/form.js +++ b/packages/replace/test/form.js @@ -1,34 +1,27 @@ /* eslint-disable consistent-return, global-require, import/no-dynamic-require */ process.chdir(__dirname); - const { readdirSync, readFileSync } = require('fs'); -const test = require('ava'); - const replace = require('..'); const transformContext = {}; - readdirSync('./fixtures/form').forEach((dir) => { let config; - try { config = require(`./fixtures/form/${dir}/_config.js`); } catch (err) { config = {}; } - - test(`${dir}: ${config.description}`, (t) => { + test(`${dir}: ${config.description}`, () => { const { transform } = replace(config.options); const extname = config.isTypescript ? 'ts' : 'js'; const input = readFileSync(`fixtures/form/${dir}/input.${extname}`, 'utf-8'); - return Promise.resolve( transform.call(transformContext, input, `${__dirname}/fixtures/form/${dir}/input.${extname}`) ).then((transformed) => { const actual = (transformed ? transformed.code : input).trim(); - t.snapshot(actual); + expect(actual).toMatchSnapshot(); }); }); }); diff --git a/packages/replace/test/function.js b/packages/replace/test/function.js index 20dab0779..010deae08 100644 --- a/packages/replace/test/function.js +++ b/packages/replace/test/function.js @@ -1,26 +1,30 @@ /* eslint-disable consistent-return, global-require, import/no-dynamic-require */ process.chdir(__dirname); - const { readdirSync } = require('fs'); -const test = require('ava'); const { rollup } = require('rollup'); const replace = require('..'); const { execute, getCodeFromBundle } = require('./helpers/util'); +const avaAssertions = { + is(actual, expected) { + expect(actual).toBe(expected); + }, + pass() { + expect(true).toBe(true); + } +}; readdirSync('./fixtures/function').forEach((dir) => { let config; - try { config = require(`./fixtures/function/${dir}/_config.js`); } catch (err) { config = {}; } - - test(`${dir}: ${config.description}`, async (t) => { + test(`${dir}: ${config.description}`, async () => { const options = Object.assign( { input: `fixtures/function/${dir}/main.js` @@ -33,11 +37,9 @@ readdirSync('./fixtures/function').forEach((dir) => { ] } ); - const bundle = await rollup(options); const code = await getCodeFromBundle(bundle); - const exports = execute(code, config.context, t); - + const exports = execute(code, config.context, avaAssertions); if (config.exports) config.exports(exports); }); }); diff --git a/packages/replace/test/misc.js b/packages/replace/test/misc.js index cedfbcfff..a844467af 100644 --- a/packages/replace/test/misc.js +++ b/packages/replace/test/misc.js @@ -2,19 +2,22 @@ const { join } = require('path'); -const test = require('ava'); const { rollup } = require('rollup'); const replace = require('..'); const { getOutputFromGenerated } = require('./helpers/util'); -test('does not mutate the values map properties', async (t) => { - const valuesMap = { ANSWER: '42' }; +test('does not mutate the values map properties', async () => { + const valuesMap = { + ANSWER: '42' + }; const bundle = await rollup({ input: 'main.js', plugins: [ - replace({ values: valuesMap }), + replace({ + values: valuesMap + }), { resolveId(id) { return id; @@ -27,13 +30,17 @@ test('does not mutate the values map properties', async (t) => { } ] }); - - const { code } = getOutputFromGenerated(await bundle.generate({ format: 'es' })); - t.is(code.trim(), 'log(42);'); - t.deepEqual(valuesMap, { ANSWER: '42' }); + const { code } = getOutputFromGenerated( + await bundle.generate({ + format: 'es' + }) + ); + expect(code.trim()).toBe('log(42);'); + expect(valuesMap).toEqual({ + ANSWER: '42' + }); }); - -test('can be configured with output plugins', async (t) => { +test('can be configured with output plugins', async () => { const bundle = await rollup({ input: 'main.js', plugins: [ @@ -49,7 +56,6 @@ test('can be configured with output plugins', async (t) => { } ] }); - const { code, map } = getOutputFromGenerated( await bundle.generate({ format: 'es', @@ -62,14 +68,11 @@ test('can be configured with output plugins', async (t) => { ] }) ); - - t.is(code.trim(), 'log("environment", "production");\n//# sourceMappingURL=main.js.map'); - t.truthy(map); + expect(code.trim()).toBe('log("environment", "production");\n//# sourceMappingURL=main.js.map'); + expect(map).toBeTruthy(); }); - process.chdir(join(__dirname, 'fixtures', 'form', 'assignment')); - -test.serial('no explicit setting of preventAssignment', async (t) => { +test.sequential('no explicit setting of preventAssignment', async () => { // eslint-disable-next-line no-undefined const possibleValues = [undefined, true, false]; for await (const value of possibleValues) { @@ -77,8 +80,12 @@ test.serial('no explicit setting of preventAssignment', async (t) => { await rollup({ input: 'input.js', onwarn: (warning) => warnings.push(warning), - plugins: [replace({ preventAssignment: value })] + plugins: [ + replace({ + preventAssignment: value + }) + ] }); - t.snapshot(warnings); + expect(warnings).toMatchSnapshot(); } }); diff --git a/packages/replace/test/snapshots/form.js.snap b/packages/replace/test/snapshots/form.js.snap index 727ba7b9fd47d860e4cf347462b788bb0911d173..2a089dfff6da476c5c5b8b3c2f2922cb785a1cef 100644 GIT binary patch literal 2417 zcmb7GO_S3&5WV|XG_HkAsIg79_LS^EK|#R<_Ao3L*qSI-I~FLCOOicIQTyL%DOPMx z5$00zL?b*1@%6jjgqVZgB~xBt9Gc|61YaIW)2KCl9dRuW3ojM3Wh9Ltp9^6Sf`EAC0d)K>hhPbUi|x- zqB9R@wo2ElQ3Z}t>9g=RIsN7UPh?tx#Ow z{;>dIfdLm)g@#Iv3MQh03wPI`u7>QZE21|P5DNKh4&R7{F=I2O581Q%D)~Pd!I(m@ zju9VHD}?m$$uyK5o#8i19u+*-_s#jX0gfBLfd@bByJog;{N@P8wC{0q;~VGN9hc6z zE?e)5UxX0T1BQEI+%Z?yS;vg3DufBdnm)$`7tsD7USeL}4FV-F6VCFxn+ni6-cIXu4&&q9^5 z2U5@P2@8%M7=EAocF`_cL;(H%_WI zpRsi5{cD3qkKpjmOZ#x}FQ^P}OV3ui*ZmMU<+br!vf91t?!jd=W@@3f%ZN5yfsdT# zd&X=g9Nj6<{FqLcj7AM6W4ll0!$GTOe|rX@b%x-OKzhg)`p9X7fBkv3zyw^R_Gl`P zt}Uxt6$oDf^TXFh48e0w`?1L&CPh5yesR(Ms8}luJC4bdliic-z|Y1jSe(6zNxPJM)M>0gnC8&u5Td!|>Yt)Hw-YaVHu>Cp&<_zJ z^3FT2KhR@LA%$G)9R@vK%uo4`_M4&|NizctbJ~nF5&s5QT8hx;(dgLcjqG>46loV$ z!VsU&z#=irVF`r6@YRICkaO9mT<$ZD81;&`r4bG7Tr6q1UYoIz9MY|CrnU9?&iTf-vO#@HAVmc literal 989 zcmV<310wuERzV!5n)r{pjeEBmcYg@zJNZ zJ}<1{NR*)7BtJa*{`pU^fU!ezGli3j==HRPcrJ`m%*H;kcxg&4nBAp7xha(ZZMrgS zbJUO-rOXxuEO)SBN(zv|mm`yCf#=LJeh~fTaT2m0-#(t50+N#2#X=HWDg_sHN9EBLGDKHziGI87ur4VhIZmN3Ts5keaUL8bPI=i zB-{-;JNpzva@Ytb#iR=WH~c&i@X%WGUeX~t9U^!=mN&ilKb1oA|fXJ(C6XHTY~ z%kMk1n%P}!3bf1_8}wE44MS2O)H-N%2iSk_u|FN&)~B;5la?HO3xwQg0V%j#T5;Yh zaHY9dOYZFz9r1VGK*X&qTr7|)X7Rf3uTBlMdI)~e1E1GA*!RYhhmRknwa0pxZT%d{HM$@`B?T8{s4Ss V$u=pj&w1zN@ty1KdGf1Y@^AMmv^M|% literal 398 zcmV;90df98RzVi0^uR?5BVh;k#+`+85Uuw1uuNBe<7BE zB14X~9v_Pc00000000A(QOimLQ4CG0R#CJq`T+qKy6^!m#f4o-L8=I%uIzOtZLi+B zcf84HyA;1daHAjL_sO7B!N2|sY->9=0iTW=(g{|&Ym`wP; z`DZ4S!oBe5Jltv4xz>2-%N$zoJGY{=A96*FJ#B)hk-CppMeCI$1fM%&y?dw{)M!~0 z0%wBdsG=CGU!cYf3(`YbJ;E(irL3 literal 379 zcmV->0fhcRRzVYuO|n!{ zEXJ0H6CP1tWZEff#MllKXCG!!B%HW>@leC!usZWk0Gt810&oYQ!-6&oF2WH>$Jl4t zYPG-`U>;Z#9acG5RMj@ylS7dT=_vi^_-udeK_C;I#b%4@Yh@_cSdRDh1+RJv;2gj; zfGL2d?-Bh%f@TrHx@JVY)V#*}r%SI_*LvcHl=en8pW%6%#nXSVxLq_L3g+{2y7?xD z7jzQ { - const locator = getLocator(code, { offsetLine: 1 }); - + const locator = getLocator(code, { + offsetLine: 1 + }); let generatedLoc = locator('42'); let loc = smc.originalPositionFor(generatedLoc); - t.snapshot(generatedLoc); - t.snapshot(loc); - + expect(generatedLoc).toMatchSnapshot(); + expect(loc).toMatchSnapshot(); generatedLoc = locator('log'); loc = smc.originalPositionFor(generatedLoc); - t.snapshot(generatedLoc); - t.snapshot(loc); + expect(generatedLoc).toMatchSnapshot(); + expect(loc).toMatchSnapshot(); }); } @@ -42,24 +41,31 @@ const testPlugin = { } } }; - -test('generates sourcemaps by default', async (t) => { +test('generates sourcemaps by default', async () => { const bundle = await rollup({ input: 'main.js', onwarn(warning) { throw new Error(warning.message); }, - plugins: [replace({ values: { ANSWER: '42' }, preventAssignment: true }), testPlugin] + plugins: [ + replace({ + values: { + ANSWER: '42' + }, + preventAssignment: true + }), + testPlugin + ] }); - const { code, map } = getOutputFromGenerated( - await bundle.generate({ format: 'es', sourcemap: true }) + await bundle.generate({ + format: 'es', + sourcemap: true + }) ); - - await verifySourcemap(code, map, t); + await verifySourcemap(code, map); }); - -test('generates sourcemaps if enabled in plugin', async (t) => { +test('generates sourcemaps if enabled in plugin', async () => { const bundle = await rollup({ input: 'main.js', onwarn(warning) { @@ -67,22 +73,24 @@ test('generates sourcemaps if enabled in plugin', async (t) => { }, plugins: [ replace({ - values: { ANSWER: '42' }, + values: { + ANSWER: '42' + }, sourcemap: true, preventAssignment: true }), testPlugin ] }); - const { code, map } = getOutputFromGenerated( - await bundle.generate({ format: 'es', sourcemap: true }) + await bundle.generate({ + format: 'es', + sourcemap: true + }) ); - - await verifySourcemap(code, map, t); + await verifySourcemap(code, map); }); - -test('generates sourcemaps if enabled in plugin (camelcase)', async (t) => { +test('generates sourcemaps if enabled in plugin (camelcase)', async () => { const bundle = await rollup({ input: 'main.js', onwarn(warning) { @@ -90,71 +98,76 @@ test('generates sourcemaps if enabled in plugin (camelcase)', async (t) => { }, plugins: [ replace({ - values: { ANSWER: '42' }, + values: { + ANSWER: '42' + }, sourceMap: true, preventAssignment: true }), testPlugin ] }); - const { code, map } = getOutputFromGenerated( - await bundle.generate({ format: 'es', sourcemap: true }) + await bundle.generate({ + format: 'es', + sourcemap: true + }) ); - - await verifySourcemap(code, map, t); + await verifySourcemap(code, map); }); - -test('does not generate sourcemaps if disabled in plugin', async (t) => { +test('does not generate sourcemaps if disabled in plugin', async () => { let warned = false; - const bundle = await rollup({ input: 'main.js', onwarn(warning) { - t.is( - warning.message, + expect(warning.message).toBe( "Sourcemap is likely to be incorrect: a plugin (replace) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help" ); warned = true; }, plugins: [ replace({ - values: { ANSWER: '42' }, + values: { + ANSWER: '42' + }, sourcemap: false, preventAssignment: true }), testPlugin ] }); - - t.truthy(!warned); - await bundle.generate({ format: 'es', sourcemap: true }); - t.truthy(warned); + expect(!warned).toBeTruthy(); + await bundle.generate({ + format: 'es', + sourcemap: true + }); + expect(warned).toBeTruthy(); }); - -test('does not generate sourcemaps if disabled in plugin (camelcase)', async (t) => { +test('does not generate sourcemaps if disabled in plugin (camelcase)', async () => { let warned = false; - const bundle = await rollup({ input: 'main.js', onwarn(warning) { - t.is( - warning.message, + expect(warning.message).toBe( "Sourcemap is likely to be incorrect: a plugin (replace) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help" ); warned = true; }, plugins: [ replace({ - values: { ANSWER: '42' }, + values: { + ANSWER: '42' + }, sourceMap: false, preventAssignment: true }), testPlugin ] }); - - t.truthy(!warned); - await bundle.generate({ format: 'es', sourcemap: true }); - t.truthy(warned); + expect(!warned).toBeTruthy(); + await bundle.generate({ + format: 'es', + sourcemap: true + }); + expect(warned).toBeTruthy(); }); diff --git a/packages/terser/package.json b/packages/terser/package.json index 3ecff3366..2106d5d88 100644 --- a/packages/terser/package.json +++ b/packages/terser/package.json @@ -28,13 +28,13 @@ "ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov", "ci:lint": "pnpm build && pnpm lint", "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}", - "ci:test": "pnpm test -- --verbose && pnpm test:ts", + "ci:test": "pnpm test -- --reporter=verbose && pnpm test:ts", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", "prerelease": "pnpm build", "pretest": "pnpm build", "release": "pnpm --workspace-root package:release $(pwd)", - "test": "ava", + "test": "vitest --config ../../.config/vitest.config.mts run", "test:ts": "tsc types/index.d.ts test/types.ts --noEmit" }, "files": [ diff --git a/packages/terser/test/test.js b/packages/terser/test/test.js index 316fb2288..78366dbc3 100644 --- a/packages/terser/test/test.js +++ b/packages/terser/test/test.js @@ -1,184 +1,237 @@ -const test = require('ava'); const { rollup } = require('rollup'); const terser = require('../'); -test.serial('minify', async (t) => { +test.sequential('minify', async () => { const bundle = await rollup({ input: 'test/fixtures/unminified.js', plugins: [terser()] }); - const result = await bundle.generate({ format: 'cjs' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'cjs' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is(output.code, '"use strict";window.a=5,window.a<3&&console.log(4);\n'); - t.falsy(output.map); + expect(output.code).toBe('"use strict";window.a=5,window.a<3&&console.log(4);\n'); + expect(output.map).toBeFalsy(); }); - -test.serial('minify with source map', async (t) => { +test.sequential('minify with source map', async () => { const bundle = await rollup({ input: 'test/fixtures/unminified.js', plugins: [terser()] }); - const result = await bundle.generate({ format: 'cjs', sourcemap: true }); - t.is(result.output.length, 2); + const result = await bundle.generate({ + format: 'cjs', + sourcemap: true + }); + expect(result.output.length).toBe(2); const [output] = result.output; - - t.truthy(output.map); - t.is(output.map.version, 3); - t.is(output.map.file, 'unminified.js'); - t.deepEqual(output.map.names, ['window', 'a', 'console', 'log']); + expect(output.map).toBeTruthy(); + expect(output.map.version).toBe(3); + expect(output.map.file).toBe('unminified.js'); + expect(output.map.names).toEqual(['window', 'a', 'console', 'log']); }); - -test.serial('minify via terser options', async (t) => { +test.sequential('minify via terser options', async () => { const bundle = await rollup({ input: 'test/fixtures/empty.js', - plugins: [terser({ output: { comments: 'all' } })] + plugins: [ + terser({ + output: { + comments: 'all' + } + }) + ] }); const result = await bundle.generate({ banner: '/* package name */', format: 'cjs' }); - t.is(result.output.length, 1); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is(output.code, '/* package name */\n"use strict";\n'); - t.falsy(output.map); + expect(output.code).toBe('/* package name */\n"use strict";\n'); + expect(output.map).toBeFalsy(); }); - -test.serial('minify multiple outputs', async (t) => { +test.sequential('minify multiple outputs', async () => { let plugin; - const bundle = await rollup({ input: 'test/fixtures/unminified.js', - plugins: [(plugin = terser({ maxWorkers: 2 }))] + plugins: [ + (plugin = terser({ + maxWorkers: 2 + })) + ] }); - const [bundle1, bundle2] = await Promise.all([ - bundle.generate({ format: 'cjs' }), - bundle.generate({ format: 'es' }) + bundle.generate({ + format: 'cjs' + }), + bundle.generate({ + format: 'es' + }) ]); const [output1] = bundle1.output; const [output2] = bundle2.output; - - t.is(output1.code, '"use strict";window.a=5,window.a<3&&console.log(4);\n'); - t.is(output2.code, 'window.a=5,window.a<3&&console.log(4);\n'); - t.is(plugin.numOfWorkersUsed, 2, 'used 2 workers'); + expect(output1.code).toBe('"use strict";window.a=5,window.a<3&&console.log(4);\n'); + expect(output2.code).toBe('window.a=5,window.a<3&&console.log(4);\n'); + expect(plugin.numOfWorkersUsed).toBe(2); }); - -test.serial('minify multiple outputs with only 1 worker', async (t) => { +test.sequential('minify multiple outputs with only 1 worker', async () => { let plugin; - const bundle = await rollup({ input: 'test/fixtures/unminified.js', - plugins: [(plugin = terser({ maxWorkers: 1 }))] + plugins: [ + (plugin = terser({ + maxWorkers: 1 + })) + ] }); - - await Promise.all([bundle.generate({ format: 'cjs' }), bundle.generate({ format: 'es' })]); - - t.is(plugin.numOfWorkersUsed, 1, 'used 1 worker'); + await Promise.all([ + bundle.generate({ + format: 'cjs' + }), + bundle.generate({ + format: 'es' + }) + ]); + expect(plugin.numOfWorkersUsed).toBe(1); }); - -test.serial('minify esm module', async (t) => { +test.sequential('minify esm module', async () => { const bundle = await rollup({ input: 'test/fixtures/plain-file.js', plugins: [terser()] }); - const result = await bundle.generate({ format: 'esm' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'esm' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is(output.code, 'console.log("bar");\n'); + expect(output.code).toBe('console.log("bar");\n'); }); - -test.serial('minify esm module with disabled module option', async (t) => { +test.sequential('minify esm module with disabled module option', async () => { const bundle = await rollup({ input: 'test/fixtures/plain-file.js', - plugins: [terser({ module: false })] + plugins: [ + terser({ + module: false + }) + ] + }); + const result = await bundle.generate({ + format: 'esm' }); - const result = await bundle.generate({ format: 'esm' }); - t.is(result.output.length, 1); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is(output.code, 'const foo="bar";console.log(foo);\n'); + expect(output.code).toBe('const foo="bar";console.log(foo);\n'); }); - -test.serial('minify cjs module', async (t) => { +test.sequential('minify cjs module', async () => { const bundle = await rollup({ input: 'test/fixtures/plain-file.js', plugins: [terser()] }); - const result = await bundle.generate({ format: 'cjs' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'cjs' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is(output.code, '"use strict";console.log("bar");\n'); + expect(output.code).toBe('"use strict";console.log("bar");\n'); }); - -test.serial('minify cjs module with disabled toplevel option', async (t) => { +test.sequential('minify cjs module with disabled toplevel option', async () => { const bundle = await rollup({ input: 'test/fixtures/plain-file.js', - plugins: [terser({ toplevel: false })] + plugins: [ + terser({ + toplevel: false + }) + ] }); - const result = await bundle.generate({ format: 'cjs' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'cjs' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is(output.code, '"use strict";const foo="bar";console.log(foo);\n'); + expect(output.code).toBe('"use strict";const foo="bar";console.log(foo);\n'); }); - -test.serial('throw error on terser fail', async (t) => { +test.sequential('throw error on terser fail', async () => { try { const bundle = await rollup({ input: 'test/fixtures/failed.js', plugins: [ { renderChunk: () => { - return { code: 'var = 1' }; + return { + code: 'var = 1' + }; } }, terser() ] }); - await bundle.generate({ format: 'esm' }); - t.falsy(true); + await bundle.generate({ + format: 'esm' + }); + expect(true).toBeFalsy(); } catch (error) { - t.is(error.toString(), 'SyntaxError: Name expected'); + expect(error.toString()).toBe('SyntaxError: Name expected'); } }); - -test.serial('throw error on terser fail with multiple outputs', async (t) => { +test.sequential('throw error on terser fail with multiple outputs', async () => { try { const bundle = await rollup({ input: 'test/fixtures/failed.js', plugins: [ { renderChunk: () => { - return { code: 'var = 1' }; + return { + code: 'var = 1' + }; } }, terser() ] }); - await Promise.all([bundle.generate({ format: 'cjs' }), bundle.generate({ format: 'esm' })]); - t.falsy(true); + await Promise.all([ + bundle.generate({ + format: 'cjs' + }), + bundle.generate({ + format: 'esm' + }) + ]); + expect(true).toBeFalsy(); } catch (error) { - t.is(error.toString(), 'SyntaxError: Name expected'); + expect(error.toString()).toBe('SyntaxError: Name expected'); } }); - -test.serial('allow to pass not string values to worker', async (t) => { +test.sequential('allow to pass not string values to worker', async () => { const bundle = await rollup({ input: 'test/fixtures/unminified.js', - plugins: [terser({ mangle: { properties: { regex: /^_/ } } })] + plugins: [ + terser({ + mangle: { + properties: { + regex: /^_/ + } + } + }) + ] + }); + const result = await bundle.generate({ + format: 'cjs' }); - const result = await bundle.generate({ format: 'cjs' }); - t.is(result.output.length, 1); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is(output.code, '"use strict";window.a=5,window.a<3&&console.log(4);\n'); + expect(output.code).toBe('"use strict";window.a=5,window.a<3&&console.log(4);\n'); }); - -test.serial('allow classic function definitions passing to worker', async (t) => { +test.sequential('allow classic function definitions passing to worker', async () => { const bundle = await rollup({ input: 'test/fixtures/commented.js', plugins: [ terser({ - mangle: { properties: { regex: /^_/ } }, + mangle: { + properties: { + regex: /^_/ + } + }, output: { comments(node, comment) { if (comment.type === 'comment2') { @@ -191,21 +244,26 @@ test.serial('allow classic function definitions passing to worker', async (t) => }) ] }); - const result = await bundle.generate({ format: 'cjs', compact: true }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'cjs', + compact: true + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is( - output.code, + expect(output.code).toBe( '"use strict";window.a=5,\n/* @preserve this comment */\nwindow.a<3&&console.log(4);' ); }); - -test.serial('allow method shorthand definitions passing to worker #2', async (t) => { +test.sequential('allow method shorthand definitions passing to worker #2', async () => { const bundle = await rollup({ input: 'test/fixtures/commented.js', plugins: [ terser({ - mangle: { properties: { regex: /^_/ } }, + mangle: { + properties: { + regex: /^_/ + } + }, output: { comments(node, comment) { if (comment.type === 'comment2') { @@ -218,26 +276,31 @@ test.serial('allow method shorthand definitions passing to worker #2', async (t) }) ] }); - const result = await bundle.generate({ format: 'cjs', compact: true }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'cjs', + compact: true + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is( - output.code, + expect(output.code).toBe( '"use strict";window.a=5,\n/* @preserve this comment */\nwindow.a<3&&console.log(4);' ); }); - -test.serial('allow arrow function definitions passing to worker', async (t) => { +test.sequential('allow arrow function definitions passing to worker', async () => { const bundle = await rollup({ input: 'test/fixtures/unminified.js', plugins: [ terser({ - mangle: { properties: { regex: /^_/ } }, + mangle: { + properties: { + regex: /^_/ + } + }, output: { comments: (node, comment) => { if (comment.type === 'comment2') { // multiline comment - return /@preserve|@license|@cc_on|^!/i.test.serial(comment.value); + return /@preserve|@license|@cc_on|^!/i.test(comment.value); } return false; } @@ -245,22 +308,32 @@ test.serial('allow arrow function definitions passing to worker', async (t) => { }) ] }); - const result = await bundle.generate({ format: 'cjs' }); - t.is(result.output.length, 1); + const result = await bundle.generate({ + format: 'cjs' + }); + expect(result.output.length).toBe(1); const [output] = result.output; - t.is(output.code, '"use strict";window.a=5,window.a<3&&console.log(4);\n'); + expect(output.code).toBe('"use strict";window.a=5,window.a<3&&console.log(4);\n'); }); - -test.serial('allow to pass not string values to worker #2', async (t) => { +test.sequential('allow to pass not string values to worker #2', async () => { const bundle = await rollup({ input: 'test/fixtures/unminified.js', - plugins: [terser({ mangle: { properties: { regex: /^_/ } } })] + plugins: [ + terser({ + mangle: { + properties: { + regex: /^_/ + } + } + }) + ] }); - const result = await bundle.generate({ format: 'cjs' }); - t.is(result.output[0].code, '"use strict";window.a=5,window.a<3&&console.log(4);\n'); + const result = await bundle.generate({ + format: 'cjs' + }); + expect(result.output[0].code).toBe('"use strict";window.a=5,window.a<3&&console.log(4);\n'); }); - -test.serial('terser accepts the nameCache option', async (t) => { +test.sequential('terser accepts the nameCache option', async () => { const nameCache = { props: { props: { @@ -281,11 +354,12 @@ test.serial('terser accepts the nameCache option', async (t) => { }) ] }); - const result = await bundle.generate({ format: 'es' }); - t.is(result.output[0].code.trim(), `console.log({foo:1,custom:2});`); + const result = await bundle.generate({ + format: 'es' + }); + expect(result.output[0].code.trim()).toBe(`console.log({foo:1,custom:2});`); }); - -test.serial('omits populates an empty nameCache object', async (t) => { +test.sequential('omits populates an empty nameCache object', async () => { const nameCache = {}; const bundle = await rollup({ input: 'test/fixtures/properties-and-locals.js', @@ -300,12 +374,13 @@ test.serial('omits populates an empty nameCache object', async (t) => { }) ] }); - const result = await bundle.generate({ format: 'es' }); - t.is( - result.output[0].code.trim(), + const result = await bundle.generate({ + format: 'es' + }); + expect(result.output[0].code.trim()).toBe( `console.log({o:1,i:2},function o(n){return n>0?o(n-1):n}(10));` ); - t.deepEqual(nameCache, { + expect(nameCache).toEqual({ props: { props: { $_priv: 'i', @@ -320,7 +395,7 @@ test.serial('omits populates an empty nameCache object', async (t) => { // Note: nameCache.vars never gets populated, but this is a Terser issue. // Here we're just testing that an empty vars object doesn't get added to nameCache if it wasn't there previously. -test.serial('terser preserve vars in nameCache when provided', async (t) => { +test.sequential('terser preserve vars in nameCache when provided', async () => { const nameCache = { vars: { props: {} @@ -339,12 +414,13 @@ test.serial('terser preserve vars in nameCache when provided', async (t) => { }) ] }); - const result = await bundle.generate({ format: 'es' }); - t.is( - result.output[0].code.trim(), + const result = await bundle.generate({ + format: 'es' + }); + expect(result.output[0].code.trim()).toBe( `console.log({o:1,i:2},function o(n){return n>0?o(n-1):n}(10));` ); - t.deepEqual(nameCache, { + expect(nameCache).toEqual({ props: { props: { $_priv: 'i', diff --git a/packages/url/package.json b/packages/url/package.json index d530941a5..2063fdb84 100644 --- a/packages/url/package.json +++ b/packages/url/package.json @@ -28,13 +28,13 @@ "ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov", "ci:lint": "pnpm build && pnpm lint", "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}", - "ci:test": "pnpm test -- --verbose", + "ci:test": "pnpm test -- --reporter=verbose", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", "prerelease": "pnpm build", "pretest": "pnpm build", "release": "pnpm --workspace-root package:release $(pwd)", - "test": "ava" + "test": "vitest --config ../../.config/vitest.config.mts run" }, "files": [ "dist", @@ -67,15 +67,5 @@ "globby": "^11.1.0", "rollup": "^4.0.0-24" }, - "types": "./types/index.d.ts", - "ava": { - "workerThreads": false, - "files": [ - "!**/fixtures/**", - "!**/output/**", - "!**/helpers/**", - "!**/recipes/**", - "!**/types.ts" - ] - } + "types": "./types/index.d.ts" } diff --git a/packages/url/test/snapshots/test.js.snap b/packages/url/test/snapshots/test.js.snap index 43e744421c736589c8e3065fadf958cbc1eeafdd..4a096f692f1b0a8f7117a56472f2ffb14b4b663c 100644 GIT binary patch literal 4712 zcmd^C+j8PK5Pjz>R8;Y_Yy^a4AgMga;4sPNf?SAvQc7euPs9|Tl??ZGKRrH z;WEk0%etttk=pKaj=H68j8UHp775h#Xb_Ekfu`jm8VeCbCm2tYxdV$$u@iHP;V88_ z7>kLU%dwZh4@GqUIP!y6ly_<9uskxkN5fZSbC*R$L6FUSqUOYok$ZWYtY-AHaD2bn#{MPhv+SWHFn@u0a2u=JL76rNOSQE2-=I971_N z7C|hq(seQSp!j@31*9RE(EIe=5)YfP4n)U&w34)d!J_ zF-yV^(b32cE$%r;_z**pXz~#Gf#ANE4aWdXARKM}BI1xm_}KhXwoO+0Vpi)lTB{s@ zK_)Kc3)|yzCm<@a5-Z+}W<69xMj;yMoO%+i(!WP1Fz8u`y$I$-lDcoBC9+IbrZT|o z2MGU=dlmVG`+XR~rbVOi{ycyGgq41u_*PW!&{v~+Uk?w$g;~hrAsY!_ZoYn)Eb)A= zDAko_IQyrm5MC;yp+pAq#7E%rjBQegw4H66I;a*r(!p!qJD3G7chZj`Q4{Pz!; zlPNWIKzjuuISf0FMFlf*m1SkDY>oNraLAE(MX#R(#9Ci;NJLpq`^&I z7k2HcJ1CEbmHy4$zzXgv(e1EuF3f>mziw1ZH-8%Cn`Vz(&CTI8UB1=m!2Nc1c9z-B zB$|!e*&3ORoSy>bs7NQ{S=MrBK^xbfaFr0F`#iktI6&P1#8Lv%#Fd%WB4wI zU9DyGhP2<;Y+L><6%bTg#Ru&uL!tB=y!BZjT1hX+{+7b+#IaM&zVD#`DBK2xZi&#f}~Aiuf`_!U$e(a)F}sL&_l*?mV2Ef%Zy z?6x{wDy{w1>0KIqmsBsbWVL3*Xjr7{C)=l1Y78zZ*c}prPD=Hg4lHVs0~`5z-%C1vq!oV6}T$hzL6^SFnrynHafMAPCe-_c8u*Pf pbzZzNO434}F|d?W$X+JRY$)lI22Pa+=2iA literal 1204 zcmV;l1WWrtRzVxl z+I@oYAs>qf00000000B!md$VDL>R{7T`iyrQB{CAa9}7c(u(XlNz-o9QqVYYvn~CI z(@na~VWqJ>cBXM{uRU(kB80@96IU*axN+nk|T#Vl(n2aR6thnnqSX#0oFj@qi zDqTm_T8*MxtFKjiSWz^!aw7G9~V$E7_-scFqNX|)uK?y(B3twywdbQZNA zZ_97cdKm8lURXy}a6`p%NrR=t@A0P8Wfd!$7Hb=8pwq_NSc8;ROPI)VJB41@pBDY| zOZ0Ry`>#{%KO3^A|8w|sc7<;M|FP^iC;%aNIwe@ad?`97)nqyyH2gaM0S;@jpmNla&U25iBG{E)+#1G z^kQpDu5z?PAZ`U?IVy{Qw8eOxS$X8N&nJ1jNO^RG$MEd>K7)~O`ln8Id8Go~_2eWDdX!XmqiphTSDbJvWOGXEb=4WVMZP3t;4L(&;N7!x#9We1GZU| zSa~}tpIxbx?quOvfX^hk8EGyfNg3%wh`5vaM7j$~7NpO;i2D(jZxWFtXeoA>RFTeH z5?nW&f43YLu5yZcjCT-o4JR@w($5jmL(hpgTnC{j-_4A>QAkI2-ng|VDQjCJw_RB$ z{FJ!zn*Jzn=`{C9FP2NBRCoyUGryPi<+RX2u0+}p?+}hUut0ohAd>|yIi+vc$qbWq zlZXVusu55E^+=FQLrzU$mKxj>o74+{1Vw|lWD(p10{T3Hd2<{^BZZAin6 z^gdiSF}iV!(X6Qb&g}wX{LzOMu@;7JPK$y#g?$A$FelUa;utz&9iCPWZ~3s2xn(-u6iSrRTd!6 z=TKYY^x7$UyCd{CoKm-oel>*7^a$?{5x!hf!ts85Gq|Kk48sdd1`+{`32(U#$-i1q SGo)d@l*T`rj@j`d6953|u2eq& diff --git a/packages/url/test/test.js b/packages/url/test/test.js index 940ad8e95..303ed8c87 100644 --- a/packages/url/test/test.js +++ b/packages/url/test/test.js @@ -1,92 +1,109 @@ const { readFileSync } = require('fs'); const { join, posix, sep, resolve } = require('path'); -const test = require('ava'); const del = require('del'); const globby = require('globby'); const { rollup } = require('rollup'); const url = require('..'); - require('source-map-support').install(); process.chdir(__dirname); - const outputFile = 'output/bundle.js'; const outputDir = 'output/'; - -const run = async (t, type, opts) => { - const defaults = { emitFiles: false, publicPath: '' }; - const options = { ...defaults, ...opts }; +const run = async (type, opts) => { + const defaults = { + emitFiles: false, + publicPath: '' + }; + const options = { + ...defaults, + ...opts + }; const bundle = await rollup({ input: `fixtures/${type}.js`, plugins: [url(options)] }); - await bundle.write({ format: 'es', file: outputFile }); + await bundle.write({ + format: 'es', + file: outputFile + }); const code = readFileSync(outputFile, 'utf-8'); // Windows fix, glob paths must be in unix format const glob = join(outputDir, `**/*.${type}`).split(sep).join(posix.sep); - - t.snapshot(code); - t.snapshot(await globby(glob)); + expect(code).toMatchSnapshot(); + expect(await globby(glob)).toMatchSnapshot(); }; - -test.beforeEach(() => del(outputDir)); - -test.serial('inline png files', async (t) => { - await run(t, 'png', { limit: 10 * 1024 }); +beforeEach(() => del(outputDir)); +test.sequential('inline png files', async () => { + await run('png', { + limit: 10 * 1024 + }); }); - -test.serial('inline jpg files', async (t) => { - await run(t, 'jpg', { limit: 10 * 1024 }); +test.sequential('inline jpg files', async () => { + await run('jpg', { + limit: 10 * 1024 + }); }); - -test.serial('inline jpeg files', async (t) => { - await run(t, 'jpeg', { limit: 10 * 1024 }); +test.sequential('inline jpeg files', async () => { + await run('jpeg', { + limit: 10 * 1024 + }); }); - -test.serial('inline gif files', async (t) => { - await run(t, 'gif', { limit: 10 * 1024 }); +test.sequential('inline gif files', async () => { + await run('gif', { + limit: 10 * 1024 + }); }); - -test.serial('inline webp files', async (t) => { - await run(t, 'webp', { limit: 10 * 1024 }); +test.sequential('inline webp files', async () => { + await run('webp', { + limit: 10 * 1024 + }); }); - -test.serial('inline text files', async (t) => { - await run(t, 'svg', { limit: 10 * 1024 }); +test.sequential('inline text files', async () => { + await run('svg', { + limit: 10 * 1024 + }); }); - -test.serial('inline "large" files', async (t) => { - await run(t, 'svg', { limit: 10 }); +test.sequential('inline "large" files', async () => { + await run('svg', { + limit: 10 + }); }); - -test.serial('limit: 0, emitFiles: false, publicPath: empty', async (t) => { - await run(t, 'svg', { limit: 0, publicPath: '', emitFiles: false }); +test.sequential('limit: 0, emitFiles: false, publicPath: empty', async () => { + await run('svg', { + limit: 0, + publicPath: '', + emitFiles: false + }); }); - -test.serial('copy files, limit: 0', async (t) => { - await run(t, 'svg', { limit: 0, emitFiles: true }); +test.sequential('copy files, limit: 0', async () => { + await run('svg', { + limit: 0, + emitFiles: true + }); }); - -test.serial('copy "large" binary files, limit: 10', async (t) => { - await run(t, 'svg', { limit: 10, emitFiles: true }); +test.sequential('copy "large" binary files, limit: 10', async () => { + await run('svg', { + limit: 10, + emitFiles: true + }); }); - -test.serial('copy files with include by absolute path, limit: 0', async (t) => { - await run(t, 'svg', { +test.sequential('copy files with include by absolute path, limit: 0', async () => { + await run('svg', { limit: 0, emitFiles: true, include: [resolve('.', 'fixtures', '*.svg')] }); }); - -test.serial('use publicPath', async (t) => { - await run(t, 'png', { limit: 10, publicPath: '/batman/' }); +test.sequential('use publicPath', async () => { + await run('png', { + limit: 10, + publicPath: '/batman/' + }); }); - -test.serial('use publicPath with file that has empty dirname', async (t) => { - await run(t, 'png', { +test.sequential('use publicPath with file that has empty dirname', async () => { + await run('png', { limit: 10, publicPath: '/batman/', emitFiles: true, @@ -94,27 +111,38 @@ test.serial('use publicPath with file that has empty dirname', async (t) => { sourceDir: join(__dirname, './fixtures') }); }); - -test.serial('create a nested directory for the output, if required', async (t) => { - await run(t, 'png', { limit: 10, emitFiles: true, fileName: 'joker/[hash][extname]' }); +test.sequential('create a nested directory for the output, if required', async () => { + await run('png', { + limit: 10, + emitFiles: true, + fileName: 'joker/[hash][extname]' + }); }); - -test.serial('create a file with the name and extension of the file', async (t) => { - await run(t, 'png', { limit: 10, emitFiles: true, fileName: '[name][extname]' }); +test.sequential('create a file with the name and extension of the file', async () => { + await run('png', { + limit: 10, + emitFiles: true, + fileName: '[name][extname]' + }); }); - -test.serial('create a file with the name, hash and extension of the file', async (t) => { - await run(t, 'png', { limit: 10, emitFiles: true, fileName: '[name]-[hash][extname]' }); +test.sequential('create a file with the name, hash and extension of the file', async () => { + await run('png', { + limit: 10, + emitFiles: true, + fileName: '[name]-[hash][extname]' + }); }); - -test.serial('prefix the file with the parent directory of the source file', async (t) => { - await run(t, 'png', { limit: 10, emitFiles: true, fileName: '[dirname][hash][extname]' }); +test.sequential('prefix the file with the parent directory of the source file', async () => { + await run('png', { + limit: 10, + emitFiles: true, + fileName: '[dirname][hash][extname]' + }); }); - -test.serial( +test.sequential( 'prefix the file with the parent directory of the source file, relative to the sourceDir option', - async (t) => { - await run(t, 'png', { + async () => { + await run('png', { limit: 10, emitFiles: true, fileName: '[dirname][hash][extname]', @@ -122,9 +150,8 @@ test.serial( }); } ); - -test.serial('copy the file according to destDir option', async (t) => { - await run(t, 'png', { +test.sequential('copy the file according to destDir option', async () => { + await run('png', { limit: 10, emitFiles: true, fileName: '[dirname][hash][extname]', diff --git a/packages/wasm/package.json b/packages/wasm/package.json index 66fc449ce..aaf91127e 100644 --- a/packages/wasm/package.json +++ b/packages/wasm/package.json @@ -28,13 +28,13 @@ "ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov", "ci:lint": "pnpm build && pnpm lint", "ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}", - "ci:test": "pnpm test -- --verbose", + "ci:test": "pnpm test -- --reporter=verbose", "prebuild": "del-cli dist", "prepare": "if [ ! -d 'dist' ]; then pnpm build; fi", "prerelease": "pnpm build", "pretest": "pnpm build", "release": "pnpm --workspace-root package:release $(pwd)", - "test": "ava", + "test": "vitest --config ../../.config/vitest.config.mts run", "test:ts": "tsc --noEmit" }, "files": [ @@ -64,7 +64,8 @@ } }, "dependencies": { - "@rollup/pluginutils": "^5.0.2" + "@rollup/pluginutils": "^5.0.2", + "types-registry": "^0.1.759" }, "devDependencies": { "@rollup/plugin-typescript": "^9.0.1", @@ -74,15 +75,6 @@ "typescript": "^4.8.3" }, "types": "./types/index.d.ts", - "ava": { - "workerThreads": false, - "files": [ - "!**/fixtures/**", - "!**/helpers/**", - "!**/recipes/**", - "!**/types.ts" - ] - }, "contributors": [ "Jamen Marz ", "Colin Eberhardt " diff --git a/packages/wasm/test/snapshots/test.mjs.snap b/packages/wasm/test/snapshots/test.mjs.snap index 164ee5e0bc51e8acd3ba3f9e39298e632fa2a943..992bd4a9a01d05855ed8c8f994c03910de188fd7 100644 GIT binary patch literal 236 zcmZ9G!3u&v6h-&*6%W_xBoRo_q7P^l)ItPb`X&b)XPEaiKR*c<)%M*>>FElv74+Lko0tE>~(D@AkgQMjxPNz>Wk3HS5$0w#I~OaUVb zfw4V7URQ8}T9pbQ@uP%Mbg^&ffwVQ4BNh2Bdm+1IqbgM&zugNzpd;`T#kjoqldY*{ R!6+%C3q7Sg8e``l;~RO$Pe1?w literal 265 zcmV+k0rvhuRzV30X=5|8 zTwuvNC;WX*QxyDM2kKef1Z`*yn|y8DgQpn6rT6#+aBoo*Dd;Ew1>I)RQhf*%gfYCh zO3F$mi+MsDq^ZFf(qi^DJ|X9SXouVP0&~*tNZ#A@AC&ZQl)?S_gay5f81pit5m(08 P`j_Vle(5TaGywnrKsj|l diff --git a/packages/wasm/test/test.mjs b/packages/wasm/test/test.mjs index 2714c87b7..80b1f21a5 100755 --- a/packages/wasm/test/test.mjs +++ b/packages/wasm/test/test.mjs @@ -5,40 +5,38 @@ import { Worker } from 'worker_threads'; import { rollup } from 'rollup'; import globby from 'globby'; -import test from 'ava'; +import { test, expect } from 'vitest'; import del from 'del'; import wasmPlugin from 'current-package'; import { getCode } from '../../../util/test.js'; +const avaAssertions = { + is(actual, expected) { + expect(actual).toBe(expected); + } +}; const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; - const DIRNAME = fileURLToPath(new URL('.', import.meta.url)); process.chdir(DIRNAME); - const outputFile = './output/bundle.js'; const outputDir = './output/'; - const testBundle = async (t, bundle) => { const code = await getCode(bundle); const func = new AsyncFunction('t', `let result;\n\n${code}\n\nreturn result;`); return func(t); }; - -test('async compiling', async (t) => { - t.plan(2); - +test('async compiling', async () => { + expect.assertions(2); const bundle = await rollup({ input: 'fixtures/async.js', plugins: [wasmPlugin()] }); - await testBundle(t, bundle); + await testBundle(avaAssertions, bundle); }); - -test('fetching WASM from separate file', async (t) => { - t.plan(3); - +test('fetching WASM from separate file', async () => { + expect.assertions(3); const bundle = await rollup({ input: 'fixtures/complex.js', plugins: [ @@ -47,31 +45,28 @@ test('fetching WASM from separate file', async (t) => { }) ] }); - - await bundle.write({ format: 'cjs', file: outputFile }); + await bundle.write({ + format: 'cjs', + file: outputFile + }); const glob = join(outputDir, `**/*.wasm`).split(sep).join(posix.sep); - global.result = null; - global.t = t; + global.t = avaAssertions; await import(outputFile); await global.result; - t.snapshot(await globby(glob)); + expect(await globby(glob)).toMatchSnapshot(); await del(outputDir); }); - -test('complex module decoding', async (t) => { - t.plan(2); - +test('complex module decoding', async () => { + expect.assertions(2); const bundle = await rollup({ input: 'fixtures/complex.js', plugins: [wasmPlugin()] }); - await testBundle(t, bundle); + await testBundle(avaAssertions, bundle); }); - -test('sync compiling', async (t) => { - t.plan(2); - +test('sync compiling', async () => { + expect.assertions(2); const bundle = await rollup({ input: 'fixtures/sync.js', plugins: [ @@ -80,12 +75,10 @@ test('sync compiling', async (t) => { }) ] }); - await testBundle(t, bundle); + await testBundle(avaAssertions, bundle); }); - -test('imports', async (t) => { - t.plan(1); - +test('imports', async () => { + expect.assertions(1); const bundle = await rollup({ input: 'fixtures/imports.js', plugins: [ @@ -94,35 +87,37 @@ test('imports', async (t) => { }) ] }); - await testBundle(t, bundle); + await testBundle(avaAssertions, bundle); }); - -test('worker', async (t) => { - t.plan(2); - +test('worker', async () => { + expect.assertions(2); const bundle = await rollup({ input: 'fixtures/worker.js', plugins: [wasmPlugin()] }); const code = await getCode(bundle); const executeWorker = () => { - const worker = new Worker(code, { eval: true }); + const worker = new Worker(code, { + eval: true + }); return new Promise((resolve, reject) => { worker.on('error', (err) => reject(err)); worker.on('exit', (exitCode) => resolve(exitCode)); }); }; - await t.notThrowsAsync(async () => { - const result = await executeWorker(); - t.true(result === 0); - }); + let error; + let result; + try { + result = await executeWorker(); + } catch (err) { + error = err; + } + expect(error).toBeUndefined(); + expect(result).toBe(0); }); - -test('injectHelper', async (t) => { - t.plan(4); - +test('injectHelper', async () => { + expect.assertions(4); const injectImport = `import { _loadWasmModule } from ${JSON.stringify('\0wasmHelpers.js')};`; - const bundle = await rollup({ input: 'fixtures/injectHelper.js', plugins: [ @@ -133,124 +128,139 @@ test('injectHelper', async (t) => { name: 'test-detect', transform: (code, id) => { if (id.endsWith('sample.wasm')) { - t.true(code.includes(injectImport)); + expect(code.includes(injectImport)).toBe(true); } if (id.endsWith('foo.js')) { - t.true(!code.includes(injectImport)); + expect(!code.includes(injectImport)).toBe(true); } return code; } } ] }); - await testBundle(t, bundle); + await testBundle(avaAssertions, bundle); }); - -test('target environment auto', async (t) => { - t.plan(5); - +test('target environment auto', async () => { + expect.assertions(5); const bundle = await rollup({ input: 'fixtures/async.js', - plugins: [wasmPlugin({ targetEnv: 'auto' })] + plugins: [ + wasmPlugin({ + targetEnv: 'auto' + }) + ] }); const code = await getCode(bundle); - await testBundle(t, bundle); - t.true(code.includes(`require("fs")`)); - t.true(code.includes(`require("path")`)); - t.true(code.includes(`fetch`)); + await testBundle(avaAssertions, bundle); + expect(code.includes(`require("fs")`)).toBe(true); + expect(code.includes(`require("path")`)).toBe(true); + expect(code.includes(`fetch`)).toBe(true); }); - -test('target environment auto-inline', async (t) => { - t.plan(6); - +test('target environment auto-inline', async () => { + expect.assertions(6); const bundle = await rollup({ input: 'fixtures/async.js', - plugins: [wasmPlugin({ targetEnv: 'auto-inline' })] + plugins: [ + wasmPlugin({ + targetEnv: 'auto-inline' + }) + ] }); const code = await getCode(bundle); - await testBundle(t, bundle); - t.true(!code.includes(`require("fs")`)); - t.true(!code.includes(`require("path")`)); - t.true(!code.includes(`fetch`)); - t.true(code.includes(`if (isNode)`)); + await testBundle(avaAssertions, bundle); + expect(!code.includes(`require("fs")`)).toBe(true); + expect(!code.includes(`require("path")`)).toBe(true); + expect(!code.includes(`fetch`)).toBe(true); + expect(code.includes(`if (isNode)`)).toBe(true); }); - -test('target environment browser', async (t) => { - t.plan(4); - +test('target environment browser', async () => { + expect.assertions(4); const bundle = await rollup({ input: 'fixtures/async.js', - plugins: [wasmPlugin({ targetEnv: 'browser' })] + plugins: [ + wasmPlugin({ + targetEnv: 'browser' + }) + ] }); const code = await getCode(bundle); - await testBundle(t, bundle); - t.true(!code.includes(`require("`)); - t.true(code.includes(`fetch`)); + await testBundle(avaAssertions, bundle); + expect(!code.includes(`require("`)).toBe(true); + expect(code.includes(`fetch`)).toBe(true); }); - -test('target environment node', async (t) => { - t.plan(4); - +test('target environment node', async () => { + expect.assertions(4); const bundle = await rollup({ input: 'fixtures/async.js', - plugins: [wasmPlugin({ targetEnv: 'node' })] + plugins: [ + wasmPlugin({ + targetEnv: 'node' + }) + ] }); const code = await getCode(bundle); - await testBundle(t, bundle); - t.true(code.includes(`require("`)); - t.true(!code.includes(`fetch`)); + await testBundle(avaAssertions, bundle); + expect(code.includes(`require("`)).toBe(true); + expect(!code.includes(`fetch`)).toBe(true); }); - -test('filename override', async (t) => { - t.plan(1); - +test('filename override', async () => { + expect.assertions(1); const bundle = await rollup({ input: 'fixtures/async.js', plugins: [ - wasmPlugin({ maxFileSize: 0, targetEnv: 'node', fileName: 'start-[name]-suffix[extname]' }) + wasmPlugin({ + maxFileSize: 0, + targetEnv: 'node', + fileName: 'start-[name]-suffix[extname]' + }) ] }); - - await bundle.write({ format: 'cjs', file: 'override/bundle.js' }); + await bundle.write({ + format: 'cjs', + file: 'override/bundle.js' + }); const glob = join('override', `start-sample-suffix.wasm`).split(sep).join(posix.sep); await import(outputFile); - t.snapshot(await globby(glob)); + expect(await globby(glob)).toMatchSnapshot(); await del('override'); }); - -test('works as CJS plugin', async (t) => { - t.plan(2); +test('works as CJS plugin', async () => { + expect.assertions(2); const require = createRequire(import.meta.url); const wasmPluginCjs = require('current-package'); const bundle = await rollup({ input: 'fixtures/async.js', plugins: [wasmPluginCjs()] }); - await testBundle(t, bundle); + await testBundle(avaAssertions, bundle); }); // uncaught exception will cause test failures on this node version. if (!process.version.startsWith('v14')) { - test('avoid uncaught exception on file read', async (t) => { - t.plan(2); - + test('avoid uncaught exception on file read', async () => { + expect.assertions(2); const bundle = await rollup({ input: 'fixtures/complex.js', - plugins: [wasmPlugin({ maxFileSize: 0, targetEnv: 'node' })] + plugins: [ + wasmPlugin({ + maxFileSize: 0, + targetEnv: 'node' + }) + ] }); - const raw = await getCode(bundle); const code = raw.replace('.wasm', '-does-not-exist.wasm'); - const executeWorker = () => { - const worker = new Worker(`let result; ${code}`, { eval: true }); + const worker = new Worker(`let result; ${code}`, { + eval: true + }); return new Promise((resolve, reject) => { worker.on('error', (err) => reject(err)); worker.on('exit', (exitCode) => resolve(exitCode)); }); }; - - const err = await t.throwsAsync(() => executeWorker()); - t.regex(err.message, /no such file or directory/); + const err = await executeWorker().catch((error) => error); + expect(err).toBeDefined(); + expect(err.message).toMatch(/no such file or directory/); }); } From 4d029fe84f1a54264399f94c35c4b81bf37d4830 Mon Sep 17 00:00:00 2001 From: CharlieHelps Date: Fri, 6 Mar 2026 02:13:27 +0000 Subject: [PATCH 2/3] chore: update pnpm lockfile for wasm types-registry --- pnpm-lock.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 56792c42b..ead5514b0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -785,6 +785,9 @@ importers: '@rollup/pluginutils': specifier: ^5.0.2 version: 5.0.4(rollup@4.0.0-24) + types-registry: + specifier: ^0.1.759 + version: 0.1.759 devDependencies: '@rollup/plugin-typescript': specifier: ^9.0.1 @@ -5117,6 +5120,9 @@ packages: typedarray-to-buffer@3.1.5: resolution: {integrity: sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==} + types-registry@0.1.759: + resolution: {integrity: sha512-eXwqLYxOd1PNI3ABaX7DsQTB1O0rcRURpzYnwiWw6x0J1o7XNQM2Pp+26YVrKbHrZQfHRq33Ixq/kh8hO6Ux3Q==} + typescript@4.8.4: resolution: {integrity: sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==} engines: {node: '>=4.2.0'} @@ -9984,6 +9990,8 @@ snapshots: dependencies: is-typedarray: 1.0.0 + types-registry@0.1.759: {} + typescript@4.8.4: {} typescript@5.9.3: {} From 9013f9f40a1295d3dc913ca17d9a85d7d1d4ada4 Mon Sep 17 00:00:00 2001 From: CharlieHelps Date: Fri, 6 Mar 2026 03:00:39 +0000 Subject: [PATCH 3/3] fix(wasm): remove accidental types-registry dependency --- packages/wasm/package.json | 3 +-- pnpm-lock.yaml | 8 -------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/packages/wasm/package.json b/packages/wasm/package.json index aaf91127e..1e8d7df03 100644 --- a/packages/wasm/package.json +++ b/packages/wasm/package.json @@ -64,8 +64,7 @@ } }, "dependencies": { - "@rollup/pluginutils": "^5.0.2", - "types-registry": "^0.1.759" + "@rollup/pluginutils": "^5.0.2" }, "devDependencies": { "@rollup/plugin-typescript": "^9.0.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ead5514b0..56792c42b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -785,9 +785,6 @@ importers: '@rollup/pluginutils': specifier: ^5.0.2 version: 5.0.4(rollup@4.0.0-24) - types-registry: - specifier: ^0.1.759 - version: 0.1.759 devDependencies: '@rollup/plugin-typescript': specifier: ^9.0.1 @@ -5120,9 +5117,6 @@ packages: typedarray-to-buffer@3.1.5: resolution: {integrity: sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==} - types-registry@0.1.759: - resolution: {integrity: sha512-eXwqLYxOd1PNI3ABaX7DsQTB1O0rcRURpzYnwiWw6x0J1o7XNQM2Pp+26YVrKbHrZQfHRq33Ixq/kh8hO6Ux3Q==} - typescript@4.8.4: resolution: {integrity: sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==} engines: {node: '>=4.2.0'} @@ -9990,8 +9984,6 @@ snapshots: dependencies: is-typedarray: 1.0.0 - types-registry@0.1.759: {} - typescript@4.8.4: {} typescript@5.9.3: {}