Skip to content

🐛 Bug: Mocha prints out command help text and ERROR: null when unexpected error in -r module occurs #5078

@khteh

Description

@khteh

Bug Report Checklist

  • I have read and agree to Mocha's Code of Conduct and Contributing Guidelines
    I have searched for related issues and issues with the faq label, but none matched my issue.
    I have 'smoke tested' the code to be tested by running it outside the real test suite to get a better sense of whether the problem is in the code under test, my usage of Mocha, or Mocha itself.
    I want to provide a PR to resolve this

Expected

Successfully run tests with mocha 10.2.0

Actual

$ ./node_modules/.bin/mocha -r ts-node/register tests/**/*.ts --reporter mocha-junit-reporter --reporter-options mochaFile=test_reports/mocha/test-results.xml --exit
(node:75854) ExperimentalWarning: `--experimental-loader` may be removed in the future; instead use `register()`:
--import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("ts-node/esm", pathToFileURL("./"));'
(Use `node --trace-warnings ...` to show where the warning was created)
mocha inspect [spec..]

Run tests with Mocha

Rules & Behavior
      --allow-uncaught       Allow uncaught errors to propagate        [boolean]
  -A, --async-only           Require all tests to use a callback (async) or
                             return a Promise                          [boolean]
  -b, --bail                 Abort ("bail") after first test failure   [boolean]
      --check-leaks          Check for global variable leaks           [boolean]
      --delay                Delay initial execution of root suite     [boolean]
      --dry-run              Report tests without executing them       [boolean]
      --exit                 Force Mocha to quit after tests complete  [boolean]
      --fail-zero            Fail test run if no test(s) encountered   [boolean]
      --forbid-only          Fail if exclusive test(s) encountered     [boolean]
      --forbid-pending       Fail if pending test(s) encountered       [boolean]
      --global, --globals    List of allowed global variables            [array]
  -j, --jobs                 Number of concurrent jobs for --parallel; use 1 to
                             run in serial
                                   [number] [default: (number of CPU cores - 1)]
  -p, --parallel             Run tests in parallel                     [boolean]
      --retries              Retry failed tests this many times         [number]
  -s, --slow                 Specify "slow" test threshold (in milliseconds)
                                                          [string] [default: 75]
  -t, --timeout, --timeouts  Specify test timeout threshold (in milliseconds)
                                                        [string] [default: 2000]
  -u, --ui                   Specify user interface    [string] [default: "bdd"]

Reporting & Output
  -c, --color, --colors                     Force-enable color output  [boolean]
      --diff                                Show diff on failure
                                                       [boolean] [default: true]
      --full-trace                          Display full stack traces  [boolean]
      --inline-diffs                        Display actual/expected differences
                                            inline within each string  [boolean]
  -R, --reporter                            Specify reporter to use
                                                      [string] [default: "spec"]
  -O, --reporter-option,                    Reporter-specific options
  --reporter-options                        (<k=v,[k1=v1,..]>)           [array]

Configuration
      --config       Path to config file   [string] [default: (nearest rc file)]
  -n, --node-option  Node or V8 option (no leading "--")                 [array]
      --package      Path to package.json for config                    [string]

File Handling
      --extension          File extension(s) to load
                                           [array] [default: ["js","cjs","mjs"]]
      --file               Specify file(s) to be loaded prior to root suite
                           execution                   [array] [default: (none)]
      --ignore, --exclude  Ignore file(s) or glob pattern(s)
                                                       [array] [default: (none)]
      --recursive          Look for tests in subdirectories            [boolean]
  -r, --require            Require module              [array] [default: (none)]
  -S, --sort               Sort test files                             [boolean]
  -w, --watch              Watch files in the current working directory for
                           changes                                     [boolean]
      --watch-files        List of paths or globs to watch               [array]
      --watch-ignore       List of paths or globs to exclude from watching
                                      [array] [default: ["node_modules",".git"]]

Test Filters
  -f, --fgrep   Only run tests containing this string                   [string]
  -g, --grep    Only run tests matching this string or regexp           [string]
  -i, --invert  Inverts --grep and --fgrep matches                     [boolean]

Positional Arguments
  spec  One or more files, directories, or globs to test
                                                     [array] [default: ["test"]]

Other Options
  -h, --help             Show usage information & exit                 [boolean]
  -V, --version          Show version number & exit                    [boolean]
      --list-interfaces  List built-in user interfaces & exit          [boolean]
      --list-reporters   List built-in reporters & exit                [boolean]

✖ ERROR: null

In fact, just executing ./node_modules/.bin/mocha itself without any input params will hit the same console output error.

Minimal, Reproducible Example

https://github.com/khteh/Node.JSRestAPI

Versions

10.2.0
v21.5.0

Additional Info

No response

Activity

jwalton

jwalton commented on Jan 22, 2024

@jwalton

I ran into this problem too. I solved it by downgrading to node 18.16.1 (not sure exactly which node version you need, but node 18.19.0 is too recent), then running mocha, then I got an actual real error message. I fixed the problem, upgraded back to node 20, and all was well.

In my particular case, the problem was in my tsconfig.json file. With:

  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    ...

things would fail, where with:

  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "node",
    ...

everything was fine.

JoshuaKGoldberg

JoshuaKGoldberg commented on Jan 24, 2024

@JoshuaKGoldberg
Member

Spooky. I played around a bit and couldn't figure out if this is a dup of #5085 or a separate root cause that happens to be throwing a null error.

changed the title [-]🐛 Bug: mocha 10.2.0 prints out command help text instead of running successfully[/-] [+]🐛 Bug: mocha 10.2.0 prints out command help text and ERROR: null with ts-node and experimental-specifier-resolution[/+] on Jan 24, 2024
stalet

stalet commented on Feb 2, 2024

@stalet
Contributor

Spooky. I played around a bit and couldn't figure out if this is a dup of #5085 or a separate root cause that happens to be throwing a null error.

It looks like the same issue.

Rob--W

Rob--W commented on Apr 27, 2025

@Rob--W
Contributor

I believe that #5074 fixed this issue,by printing the actual error from the handler instead of triggering a new one that ends up logging ERROR: null.

There is still a potentially actionable task, but in the yargs repo, because the null in ERROR: null comes from yargs. If anyone is interested in trying that further, see #5048 (comment)

Rob--W

Rob--W commented on Apr 27, 2025

@Rob--W
Contributor

Well, a bugfix could also be made in mocha. Instead of printing msg, it could fall back to logging error at

mocha/lib/cli/cli.js

Lines 60 to 65 in abf3dd9

.fail((msg, err, yargs) => {
debug('caught error sometime before command handler: %O', err);
yargs.showHelp();
console.error(`\n${symbols.error} ${pc.red('ERROR:')} ${msg}`);
process.exit(1);
})

JoshuaKGoldberg

JoshuaKGoldberg commented on May 1, 2025

@JoshuaKGoldberg
Member

I believe that #5074 fixed this issue

I also think #5074 fixed this issue. Nice catch, thank you!

bugfix could also be made in mocha

@Rob--W is there any situation where we'd want to add a log of the error (i.e. #5344)? As in: do you have a reproduction showing any still-buggy behavior?

added
status: waiting for authorwaiting on response from OP or other posters - more information needed
and removed on May 1, 2025
JoshuaKGoldberg

JoshuaKGoldberg commented on Jun 11, 2025

@JoshuaKGoldberg
Member

Oh, sorry @Rob--W - I'd missed #5344 (comment) 😬 till now. Copying here:

For clarity, this is not about fixing whatever that triggered the error, but about improving the logged diagnostics information when an error (unexpectedly) happens.

While the specific trigger was fixed, it is still possible to end up in this case if some other internal error occurs. If you want to reproduce locally, you could throw an error from

console.error('\n Exception during run:', err);

There are probably other ways to trigger this issue, but I haven't looked.

If you are concerned about logging too much information (when an error message is already present), I could add a check to only log the error when the message is null.

Agreed on that last point, I don't think we want to log the full raw error in all cases. Only when msg is falsy then it does make sense to expand the logging IMO.

Proposal: let's...

  • Only add the extra console.error(error) when msg is falsy, and add some note about it being an unknown internal error
  • Add a test case that triggers it
    • Since ts-node et al. are fixed, this can be done either by mocking or by using an intentionally error-y replacement

cc @mochajs/committers - WDYT?

added
status: in triagea maintainer should (re-)triage (review) this issue
and removed
status: waiting for authorwaiting on response from OP or other posters - more information needed
on Jun 11, 2025
changed the title [-]🐛 Bug: mocha 10.2.0 prints out command help text and ERROR: null with ts-node and experimental-specifier-resolution[/-] [+]🐛 Bug: mocha 10.2.0 prints out command help text and ERROR: null when unexpected error in -r module occurs[/+] on Jun 11, 2025
added and removed
status: in triagea maintainer should (re-)triage (review) this issue
on Jul 12, 2025
mark-wiemer

mark-wiemer commented on Jul 12, 2025

@mark-wiemer
Member

@voxpelli FYI marking this as accepting PRs as I'm in agreement with Josh

changed the title [-]🐛 Bug: mocha 10.2.0 prints out command help text and ERROR: null when unexpected error in -r module occurs[/-] [+]🐛 Bug: Mocha prints out command help text and ERROR: null when unexpected error in -r module occurs[/+] on Aug 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: accepting prsMocha can use your help with this one!type: buga defect, confirmed by a maintainer

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

      Participants

      @stalet@Rob--W@jwalton@JoshuaKGoldberg@khteh

      Issue actions

        🐛 Bug: Mocha prints out command help text and ERROR: null when unexpected error in -r module occurs · Issue #5078 · mochajs/mocha