mochajs / mocha

☕️ simple, flexible, fun javascript test framework for node.js & the browser
https://mochajs.org
MIT License
22.63k stars 3.02k forks source link

🚀 Feature: Support algorithmically setting loader #5016

Closed FFdhorkin closed 10 months ago

FFdhorkin commented 1 year ago

Is your feature request related to a problem or a nice-to-have?? Please describe.

I can successfully run my tests on CLI by running mocha --loader=ts-node/esm. However, I need to be able to do this algorithmically, not via CLI, and there doesn't appear to be any way to do so.

Because of this, when I run await mocha.loadFilesAsync();, I get an exception: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

Describe the solution you'd like

const mocha = new Mocha({ loader: "ts-node/esm" });

Describe alternatives you've considered

I've tried adding loader to mocha.opts and package.json and .mocharc.json and it doesn't seem to pick any of these up when run programmatically.

nwalters512 commented 1 year ago

The loader option is a feature of Node itself, not Mocha, and is passed directly through to the Node binary via this file: https://github.com/mochajs/mocha/blob/master/bin/mocha.js. There's no way to provide --loader from within an existing Node process.

Note that if you're running Node 20.6+, you can use the module.register API to do something essentially equivalent at runtime: https://nodejs.org/api/module.html#moduleregisterspecifier-parenturl-options. I don't think ts-node uses this yet, though I think tsx might.

JoshuaKGoldberg commented 10 months ago

Yup, the module.register API is the way to do this!

https://github.com/mochajs/mocha-examples/issues/75 -> https://github.com/mochajs/mocha-examples/pull/76 has examples showing very straightforward on-the-fly transpilation: one with ts-node, the other with tsx. If you're looking for a more algorithmic/fancy example than that then I'd suggest posting an issue over on that repo.

Thanks all! 🤎