Skip to content

Commit

Permalink
fix: resolve file field correctly for exports mocha interface (#949)
Browse files Browse the repository at this point in the history
  • Loading branch information
shadowusr authored Jun 14, 2024
1 parent de2f5b4 commit 99a7ed1
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/test-reader/mocha-reader/tree-builder-decorator.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const { Suite, Test, Hook } = require("../test-object");
const crypto = require("../../utils/crypto");
const { computeFile } = require("./utils");

class TreeBuilderDecorator {
#treeBuilder;
Expand All @@ -17,7 +18,9 @@ class TreeBuilderDecorator {
}

addSuite(mochaSuite) {
const { id: mochaId, file } = mochaSuite;
const { id: mochaId } = mochaSuite;
const file = computeFile(mochaSuite) ?? "unknown-file";

const positionInFile = this.#suiteCounter.get(file) || 0;
const id = mochaSuite.root ? mochaId : crypto.getShortMD5(file) + positionInFile;
const suite = this.#mkTestObject(Suite, mochaSuite, { id });
Expand Down
64 changes: 64 additions & 0 deletions src/test-reader/mocha-reader/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// When using "exports" mocha interface, "file" field is absent on suites, and available on tests only.
// This helper tries to resolve "file" field for suites, drilling down to child tests and using their file field.

const findTopmostSuite = mochaSuite => {
if (mochaSuite.parent && mochaSuite.parent.root) {
return mochaSuite;
}

if (!mochaSuite.parent) {
return null;
}

return findTopmostSuite(mochaSuite.parent);
};

const getFile = mochaSuite => {
if (mochaSuite.file) {
return mochaSuite.file;
}

if (mochaSuite.tests.length > 0 && mochaSuite.tests[0].file) {
return mochaSuite.tests[0].file;
}

for (const childSuite of mochaSuite.suites) {
const computedFile = getFile(childSuite);
if (computedFile) {
return computedFile;
}
}

return null;
};

const fillSuitesFileField = (mochaSuite, file) => {
mochaSuite.file = file;

if (mochaSuite.suites) {
for (const childSuite of mochaSuite.suites) {
fillSuitesFileField(childSuite, file);
}
}
};

const computeFile = mochaSuite => {
if (mochaSuite.file) {
return mochaSuite.file;
}

const topmostSuite = findTopmostSuite(mochaSuite);
const file = topmostSuite && getFile(topmostSuite);

if (topmostSuite && file) {
fillSuitesFileField(topmostSuite, file);

return file;
}

return null;
};

module.exports = {
computeFile,
};

0 comments on commit 99a7ed1

Please sign in to comment.