qunitx 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.dockerignore +1 -0
  2. package/README.md +95 -34
  3. package/build.js +54 -0
  4. package/deno.json +2 -2
  5. package/deno.lock +3 -3744
  6. package/package.json +27 -43
  7. package/{index.js → shims/browser/index.js} +2 -4
  8. package/shims/deno/assert.js +228 -0
  9. package/shims/{deno.js → deno/index.js} +1 -1
  10. package/shims/node/assert.js +222 -0
  11. package/shims/{nodejs.js → node/index.js} +2 -2
  12. package/shims/shared/index.js +29 -0
  13. package/vendor/package.json +1 -4
  14. package/cli.js +0 -25
  15. package/deno/cli.js +0 -21
  16. package/lib/boilerplates/default-project-config-values.js +0 -6
  17. package/lib/boilerplates/setup/tests.hbs +0 -15
  18. package/lib/boilerplates/setup/tsconfig.json +0 -109
  19. package/lib/boilerplates/test.js +0 -25
  20. package/lib/commands/generate.js +0 -33
  21. package/lib/commands/help.js +0 -38
  22. package/lib/commands/init.js +0 -70
  23. package/lib/commands/run/tests-in-browser.js +0 -162
  24. package/lib/commands/run.js +0 -119
  25. package/lib/servers/http.js +0 -233
  26. package/lib/setup/bind-server-to-port.js +0 -14
  27. package/lib/setup/browser.js +0 -55
  28. package/lib/setup/config.js +0 -46
  29. package/lib/setup/file-watcher.js +0 -72
  30. package/lib/setup/fs-tree.js +0 -48
  31. package/lib/setup/keyboard-events.js +0 -34
  32. package/lib/setup/test-file-paths.js +0 -79
  33. package/lib/setup/web-server.js +0 -241
  34. package/lib/setup/write-output-static-files.js +0 -22
  35. package/lib/tap/display-final-result.js +0 -15
  36. package/lib/tap/display-test-result.js +0 -73
  37. package/lib/utils/find-internal-assets-from-html.js +0 -16
  38. package/lib/utils/find-project-root.js +0 -17
  39. package/lib/utils/indent-string.js +0 -11
  40. package/lib/utils/listen-to-keyboard-key.js +0 -44
  41. package/lib/utils/parse-cli-flags.js +0 -57
  42. package/lib/utils/path-exists.js +0 -11
  43. package/lib/utils/resolve-port-number-for.js +0 -27
  44. package/lib/utils/run-user-module.js +0 -18
  45. package/lib/utils/search-in-parent-directories.js +0 -15
  46. package/lib/utils/time-counter.js +0 -8
  47. package/shims/deno-assert.js +0 -55
  48. package/shims/nodejs-assert.js +0 -55
@@ -1,6 +0,0 @@
1
- export default {
2
- output: 'tmp',
3
- timeout: 20000,
4
- failFast: false,
5
- port: 1234
6
- }
@@ -1,15 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width">
6
- <title>{{applicationName}} Tests</title>
7
- <link href="../node_modules/qunitx/vendor/qunit.css" rel="stylesheet">
8
- </head>
9
- <body>
10
- <div id="qunit"></div>
11
- <div id="qunit-fixture"></div>
12
-
13
- {{content}}
14
- </body>
15
- </html>
@@ -1,109 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- // "jsx": "preserve", /* Specify what JSX code is generated. */
17
- // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
-
27
- /* Modules */
28
- "module": "NodeNext", /* Specify what module code is generated. */
29
- // "rootDir": ".", /* Specify the root folder within your source files. */
30
- "moduleResolution": "NodeNext", /* Specify how TypeScript looks up a file from a given module specifier. */
31
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
- // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
- // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
- // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
- // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
- // "resolveJsonModule": true, /* Enable importing .json files. */
43
- // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45
-
46
- /* JavaScript Support */
47
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50
-
51
- /* Emit */
52
- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58
- // "outDir": "./", /* Specify an output folder for all emitted files. */
59
- // "removeComments": true, /* Disable emitting comments. */
60
- // "noEmit": true, /* Disable emitting files from a compilation. */
61
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68
- // "newLine": "crlf", /* Set the newline character for emitting files. */
69
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75
-
76
- /* Interop Constraints */
77
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78
- // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83
-
84
- /* Type Checking */
85
- "strict": true, /* Enable all strict type-checking options. */
86
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104
-
105
- /* Completeness */
106
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
108
- }
109
- }
@@ -1,25 +0,0 @@
1
- import { module, test } from 'qunitx';
2
-
3
- module('{{moduleName}}', function(hooks) {
4
- test('assert true works', function (assert) {
5
- assert.expect(3);
6
- assert.ok(true);
7
- assert.equal(true, true);
8
- assert.deepEqual({}, {});
9
- });
10
-
11
- test('async test finishes', async function (assert) {
12
- assert.expect(3);
13
-
14
- let wait = () => new Promise((resolve, reject) => {
15
- setTimeout(() => resolve(true), 50);
16
- });
17
- let result = await wait();
18
-
19
- assert.ok(true);
20
- assert.equal(true, result);
21
-
22
- await wait();
23
- assert.equal(true, result);
24
- });
25
- });
@@ -1,33 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import { dirname } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import kleur from 'kleur';
5
- import findProjectRoot from '../utils/find-project-root.js';
6
- import pathExists from '../utils/path-exists.js';
7
-
8
- const __dirname = dirname(fileURLToPath(import.meta.url));
9
-
10
- export default async function() {
11
- let projectRoot = await findProjectRoot();
12
- let moduleName = process.argv[3]; // TODO: classify this maybe in future
13
- let path = process.argv[3].endsWith('.js') || process.argv[3].endsWith('.ts')
14
- ? `${projectRoot}/${process.argv[3]}`
15
- : `${projectRoot}/${process.argv[3]}.js`;
16
-
17
- if (await pathExists(path)) {
18
- return console.log(`${path} already exists!`);
19
- }
20
-
21
- let testJSContent = await fs.readFile(`${__dirname}/../boilerplates/test.js`);
22
- let targetFolderPaths = path.split('/');
23
-
24
- targetFolderPaths.pop();
25
-
26
- await fs.mkdir(targetFolderPaths.join('/'), { recursive: true });
27
- await fs.writeFile(
28
- path,
29
- testJSContent.toString().replace('{{moduleName}}', moduleName)
30
- );
31
-
32
- console.log(kleur.green(`${path} written`));
33
- }
@@ -1,38 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import { dirname } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import kleur from 'kleur';
5
-
6
- const __dirname = dirname(fileURLToPath(import.meta.url));
7
- const highlight = (text) => kleur.magenta().bold(text);
8
- const color = (text) => kleur.blue(text);
9
-
10
-
11
- export default async function() {
12
- const config = JSON.parse((await fs.readFile(`${__dirname}/../../package.json`)));
13
-
14
- console.log(`${highlight("[qunitx v" + config.version + "] Usage:")} qunitx ${color('[targets] --$flags')}
15
-
16
- ${highlight("Input options:")}
17
- - File: $ ${color('qunitx test/foo.js')}
18
- - Folder: $ ${color('qunitx test/login')}
19
- - Globs: $ ${color('qunitx test/**/*-test.js')}
20
- - Combination: $ ${color('qunitx test/foo.js test/bar.js test/*-test.js test/logout')}
21
-
22
- ${highlight("Optional flags:")}
23
- ${color('--browser')} : run qunit tests in chromium with puppeteer instead of node.js(which is the default)
24
- ${color('--debug')} : print console output when tests run in browser
25
- ${color('--watch')} : run the target file or folders, watch them for continuous run and expose http server under localhost
26
- ${color('--timeout')} : change default timeout per test case
27
- ${color('--output')} : folder to distribute built qunitx html and js that a webservers can run[default: tmp]
28
- ${color('--failFast')} : run the target file or folders with immediate abort if a single test fails
29
- ${color('--before')} : run a script before the tests(i.e start a new web server before tests)
30
- ${color('--after')} : run a script after the tests(i.e save test results to a file)
31
-
32
- ${highlight("Example:")} $ ${color('qunitx test/foo.ts app/e2e --browser --debug --watch --before=scripts/start-new-webserver.js --after=scripts/write-test-results.js')}
33
-
34
- ${highlight("Commands:")}
35
- ${color('$ qunitx init')} # Bootstraps qunitx base html and add qunitx config to package.json if needed
36
- ${color('$ qunitx new $testFileName')} # Creates a qunitx test file
37
- `);
38
- }
@@ -1,70 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path, { dirname } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import findProjectRoot from '../utils/find-project-root.js';
5
- import pathExists from '../utils/path-exists.js';
6
- import defaultProjectConfigValues from '../boilerplates/default-project-config-values.js';
7
-
8
- const __dirname = dirname(fileURLToPath(import.meta.url));
9
-
10
- export default async function() {
11
- let projectRoot = await findProjectRoot();
12
- let oldPackageJSON = JSON.parse(await fs.readFile(`${projectRoot}/package.json`));
13
- let htmlPaths = process.argv.slice(2).reduce((result, arg) => {
14
- if (arg.endsWith('.html')) {
15
- result.push(arg);
16
- }
17
-
18
- return result;
19
- }, oldPackageJSON.qunitx && oldPackageJSON.qunitx.htmlPaths ? oldPackageJSON.qunitx.htmlPaths : []);
20
- let newQunitxConfig = Object.assign(
21
- defaultProjectConfigValues,
22
- htmlPaths.length > 0 ? { htmlPaths } : { htmlPaths: ['test/tests.html'] },
23
- oldPackageJSON.qunitx
24
- );
25
-
26
- await Promise.all([
27
- writeTestsHTML(projectRoot, newQunitxConfig, oldPackageJSON),
28
- rewritePackageJSON(projectRoot, newQunitxConfig, oldPackageJSON),
29
- writeTSConfigIfNeeded(projectRoot)
30
- ]);
31
- }
32
-
33
- async function writeTestsHTML(projectRoot, newQunitxConfig, oldPackageJSON) {
34
- let testHTMLTemplateBuffer = await fs.readFile(`${__dirname}/../boilerplates/setup/tests.hbs`);
35
-
36
- return await Promise.all(newQunitxConfig.htmlPaths.map(async (htmlPath) => {
37
- let targetPath = `${projectRoot}/${htmlPath}`;
38
- if (await pathExists(targetPath)) {
39
- return console.log(`${htmlPath} already exists`);
40
- } else {
41
- let targetDirectory = path.dirname(targetPath);
42
- let targetOutputPath = path.relative(targetDirectory, `${projectRoot}/${newQunitxConfig.output}/tests.js`);
43
- let testHTMLTemplate = testHTMLTemplateBuffer
44
- .toString()
45
- .replace('{{applicationName}}', oldPackageJSON.name);
46
-
47
- await fs.mkdir(targetDirectory, { recursive: true });
48
- await fs.writeFile(targetPath, testHTMLTemplate);
49
-
50
- console.log(`${targetPath} written`);
51
- }
52
- }));
53
- }
54
-
55
- async function rewritePackageJSON(projectRoot, newQunitxConfig, oldPackageJSON) {
56
- let newPackageJSON = Object.assign(oldPackageJSON, { qunitx: newQunitxConfig });
57
-
58
- await fs.writeFile(`${projectRoot}/package.json`, JSON.stringify(newPackageJSON, null, 2));
59
- }
60
-
61
- async function writeTSConfigIfNeeded(projectRoot) {
62
- let targetPath = `${projectRoot}/tsconfig.json`;
63
- if (!(await pathExists(targetPath))) {
64
- let tsConfigTemplateBuffer = await fs.readFile(`${__dirname}/../boilerplates/setup/tsconfig.json`);
65
-
66
- await fs.writeFile(targetPath, tsConfigTemplateBuffer);
67
-
68
- console.log(`${targetPath} written`);
69
- }
70
- }
@@ -1,162 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import { dirname } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import kleur from 'kleur';
5
- import esbuild from 'esbuild';
6
- import timeCounter from '../../utils/time-counter.js';
7
- import runUserModule from '../../utils/run-user-module.js';
8
- import TAPDisplayFinalResult from '../../tap/display-final-result.js';
9
-
10
- const __dirname = dirname(fileURLToPath(import.meta.url));
11
-
12
- class BundleError extends Error {
13
- constructor(message) {
14
- super(message);
15
- this.name = 'BundleError';
16
- this.message = `esbuild Bundle Error: ${message}`.split('\n').join('\n# ');
17
- }
18
- }
19
-
20
- export default async function runTestsInBrowser(
21
- config,
22
- cachedContent = {},
23
- connections,
24
- targetTestFilesToFilter
25
- ) {
26
- const { projectRoot, timeout, output } = config;
27
- const allTestFilePaths = Object.keys(config.fsTree);
28
- const runHasFilter = !!targetTestFilesToFilter;
29
-
30
- config.COUNTER = { testCount: 0, failCount: 0, skipCount: 0, passCount: 0 };
31
- config.lastRanTestFiles = targetTestFilesToFilter || allTestFilePaths;
32
-
33
- try {
34
- await Promise.all([
35
- esbuild.build({
36
- stdin: {
37
- contents: allTestFilePaths.reduce((result, fileAbsolutePath) => {
38
- return result + `import "${fileAbsolutePath}";`
39
- }, ''),
40
- resolveDir: process.cwd()
41
- },
42
- bundle: true,
43
- logLevel: 'error',
44
- outfile: `${projectRoot}/${output}/tests.js`,
45
- keepNames: true
46
- }), // NOTE: This prevents file cache most likely
47
- Promise.all(cachedContent.htmlPathsToRunTests.map(async (htmlPath) => {
48
- let targetPath = `${config.projectRoot}/${config.output}${htmlPath}`;
49
-
50
- if (htmlPath !== '/') {
51
- await fs.rm(targetPath, { force: true, recursive: true });
52
- await fs.mkdir(targetPath.split('/').slice(0, -1).join('/'), { recursive: true }); // NOTE: this can be done earlier
53
- }
54
- }))
55
- ]);
56
- cachedContent.allTestCode = await fs.readFile(`${projectRoot}/${output}/tests.js`);
57
-
58
- if (runHasFilter) {
59
- let outputPath = `${projectRoot}/${output}/filtered-tests.js`;
60
-
61
- await buildFilteredTests(targetTestFilesToFilter, outputPath);
62
- cachedContent.filteredTestCode = (await fs.readFile(outputPath)).toString();
63
- }
64
-
65
- let TIME_COUNTER = timeCounter();
66
-
67
- if (runHasFilter) {
68
- await runTestInsideHTMLFile('/qunitx.html', connections, config);
69
- } else {
70
- await Promise.all(cachedContent.htmlPathsToRunTests.map((htmlPath) => {
71
- return runTestInsideHTMLFile(htmlPath, connections, config); // NOTE: maybe make this blocking
72
- }));
73
- }
74
-
75
- let TIME_TAKEN = TIME_COUNTER.stop()
76
-
77
- TAPDisplayFinalResult(config.COUNTER, TIME_TAKEN);
78
-
79
- if (config.after) {
80
- await runUserModule(`${process.cwd()}/${config.after}`, config.COUNTER, 'after');
81
- }
82
-
83
- if (!config.watch) {
84
- await Promise.all([
85
- connections.server && connections.server.close(),
86
- connections.browser && connections.browser.close()
87
- ]);
88
-
89
- return process.exit(config.COUNTER.failCount > 0 ? 1 : 0);
90
- }
91
- } catch(error) {
92
- config.lastFailedTestFiles = config.lastRanTestFiles;
93
- console.log(error);
94
- let exception = new BundleError(error);
95
-
96
- if (config.watch) {
97
- console.log(`# ${exception}`);
98
- } else {
99
- throw exception;
100
- }
101
- }
102
-
103
- return connections;
104
- }
105
-
106
- function buildFilteredTests(filteredTests, outputPath) {
107
- return esbuild.build({
108
- stdin: {
109
- contents: filteredTests.reduce((result, fileAbsolutePath) => {
110
- return result + `import "${fileAbsolutePath}";`
111
- }, ''),
112
- resolveDir: process.cwd()
113
- },
114
- bundle: true,
115
- logLevel: 'error',
116
- outfile: outputPath
117
- });
118
- }
119
-
120
- async function runTestInsideHTMLFile(filePath, { page, server }, config) {
121
- let QUNIT_RESULT;
122
- let targetError;
123
- try {
124
- await wait(350);
125
- console.log('#', kleur.blue(`QUnitX running: http://localhost:${config.port}${filePath}`));
126
- await page.goto(`http://localhost:${config.port}${filePath}`, { timeout: 0 });
127
- await page.evaluate(() => {
128
- window.IS_PUPPETEER = true;
129
- });
130
- await page.waitForFunction(`window.testTimeout >= ${config.timeout}`, { timeout: 0 });
131
-
132
- QUNIT_RESULT = await page.evaluate(() => window.QUNIT_RESULT);
133
- } catch(error) {
134
- targetError = error;
135
- console.log(error);
136
- console.error(error);
137
- }
138
-
139
- if (!QUNIT_RESULT || QUNIT_RESULT.totalTests === 0) {
140
- console.log(targetError);
141
- console.log('BROWSER: runtime error thrown during executing tests');
142
- console.error('BROWSER: runtime error thrown during executing tests');
143
-
144
- await failOnNonWatchMode(config.watch);
145
- } else if (QUNIT_RESULT.totalTests > QUNIT_RESULT.finishedTests) {
146
- console.log(targetError);
147
- console.log(`BROWSER: TEST TIMED OUT: ${QUNIT_RESULT.currentTest}`);
148
- console.error(`BROWSER: TEST TIMED OUT: ${QUNIT_RESULT.currentTest}`);
149
-
150
- await failOnNonWatchMode(config.watch);
151
- }
152
- }
153
-
154
- async function failOnNonWatchMode(watchMode = false) {
155
- if (!watchMode) {
156
- await new Promise((resolve, reject) => setTimeout(() => resolve(process.exit(1)), 100));
157
- }
158
- }
159
-
160
- function wait(duration) {
161
- return new Promise((resolve) => setTimeout(() => { resolve() }, duration));
162
- }
@@ -1,119 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import { normalize, dirname } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import kleur from 'kleur';
5
- import runTestsInBrowser from './run/tests-in-browser.js';
6
- import setupBrowser from '../setup/browser.js';
7
- import fileWatcher from '../setup/file-watcher.js';
8
- import findInternalAssetsFromHTML from '../utils/find-internal-assets-from-html.js';
9
- import runUserModule from '../utils/run-user-module.js';
10
- import setupKeyboardEvents from '../setup/keyboard-events.js';
11
- import writeOutputStaticFiles from '../setup/write-output-static-files.js';
12
-
13
- const __dirname = dirname(fileURLToPath(import.meta.url));
14
-
15
- export default async function(config) {
16
- let cachedContent = await buildCachedContent(config, config.htmlPaths);
17
- let [connections, _] = await Promise.all([
18
- setupBrowser(config, cachedContent),
19
- writeOutputStaticFiles(config, cachedContent)
20
- ]);
21
- config.expressApp = connections.server;
22
-
23
- if (config.watch) {
24
- setupKeyboardEvents(config, cachedContent, connections);
25
- }
26
-
27
- if (config.before) {
28
- await runUserModule(`${process.cwd()}/${config.before}`, config, 'before');
29
- }
30
-
31
- await runTestsInBrowser(config, cachedContent, connections);
32
-
33
- if (config.watch) {
34
- logWatcherAndKeyboardShortcutInfo(config, connections.server);
35
-
36
- await fileWatcher(
37
- config.testFileLookupPaths,
38
- config,
39
- async (event, file) => {
40
- if (event === 'addDir') {
41
- return;
42
- } else if (['unlink', 'unlinkDir'].includes(event)) {
43
- return await runTestsInBrowser(config, cachedContent, connections);
44
- }
45
-
46
- await runTestsInBrowser(config, cachedContent, connections, [file]);
47
- },
48
- (path, event) => connections.server.publish('refresh', 'refresh')
49
- );
50
- }
51
- }
52
-
53
- async function buildCachedContent(config, htmlPaths) {
54
- let htmlBuffers = await Promise.all(config.htmlPaths.map((htmlPath) => fs.readFile(htmlPath))); // TODO: remove this and read it from the fsTree, should be cached?
55
- let cachedContent = htmlPaths.reduce((result, htmlPath, index) => {
56
- let filePath = config.htmlPaths[index];
57
- let html = htmlBuffers[index].toString();
58
-
59
- if (html.includes('{{content}}')) { // TODO: here I could do html analysis to see which static js certain html points to? Complex algorithm
60
- result.dynamicContentHTMLs[filePath] = html;
61
-
62
- let relativePath = filePath.replace(config.projectRoot, '');
63
-
64
- result.htmlPathsToRunTests.push(relativePath);
65
- } else {
66
- console.log('#', kleur.yellow(`WARNING: Static html file with no {{content}} detected. Therefore ignoring ${filePath}`));
67
- result.staticHTMLs[filePath] = html;
68
- }
69
-
70
- findInternalAssetsFromHTML(html).forEach((key) => {
71
- result.assets.add(normalizeInternalAssetPathFromHTML(config.projectRoot, key, filePath))
72
- });
73
-
74
- return result;
75
- }, {
76
- allTestCode: null,
77
- assets: new Set(),
78
- htmlPathsToRunTests: [],
79
- mainHTML: { filePath: null, html: null },
80
- staticHTMLs: {},
81
- dynamicContentHTMLs: {}
82
- });
83
-
84
- if (cachedContent.htmlPathsToRunTests.length === 0) {
85
- cachedContent.htmlPathsToRunTests = ['/'];
86
- }
87
-
88
- return await addCachedContentMainHTML(config.projectRoot, cachedContent);
89
- }
90
-
91
- async function addCachedContentMainHTML(projectRoot, cachedContent) {
92
- let mainHTMLPath = Object.keys(cachedContent.dynamicContentHTMLs)[0];
93
- if (mainHTMLPath) {
94
- cachedContent.mainHTML = {
95
- filePath: mainHTMLPath,
96
- html: cachedContent.dynamicContentHTMLs[mainHTMLPath]
97
- };
98
- } else {
99
- let html = (await fs.readFile(`${__dirname}/../boilerplates/setup/tests.hbs`)).toString();
100
-
101
- cachedContent.mainHTML = { filePath: `${projectRoot}/test/tests.html`, html };
102
- cachedContent.assets.add(`${projectRoot}/node_modules/qunitx/vendor/qunit.css`);
103
- }
104
-
105
- return cachedContent;
106
- }
107
-
108
- function logWatcherAndKeyboardShortcutInfo(config, server) {
109
- console.log('#', kleur.blue(`Watching files... You can browse the tests on http://localhost:${config.port} ...`)); // NOTE: maybe add also qx to exit
110
- console.log('#', kleur.blue(`Shortcuts: Press "qq" to abort running tests, "qa" to run all the tests, "qf" to run last failing test, "ql" to repeat last test`)); // NOTE: maybe add also qx to test specific
111
- }
112
-
113
- function normalizeInternalAssetPathFromHTML(projectRoot, assetPath, htmlPath) { // NOTE: maybe normalize ..
114
- let currentDirectory = htmlPath ? htmlPath.split('/').slice(0, -1).join('/') : projectRoot;
115
-
116
- return assetPath.startsWith('./')
117
- ? normalize(`${currentDirectory}/${assetPath.slice(2)}`)
118
- : normalize(`${currentDirectory}/${assetPath}`);
119
- }