Home > Mobile >  Mocha and ts-node gives 'Unsupported Args'
Mocha and ts-node gives 'Unsupported Args'

Time:11-17

In my package.json I have defined my test script:

"scripts": {
    "test": "mocha --require ts-node/register ./test/**/*.ts",
    "build": "npx tsc"
}

When I run npm test I get back the result:

> mocha --require ts-node/register ./test/**/*.ts

error:   Unsupported Args: --require ts-node/register ./test/**/*.ts

It seems to somehow be the command interaction. Even if I run it manually node .\node_modules\mocha\bin\mocha --require ts-node/register "./test/**/*.ts" it fails with the same message. If I remove --require ts-node/register it runs, but fails when running the test on import statements because my test files are Typescript files.

How do I make mocha work with ts-node?

CodePudding user response:

My package.json file has it in scripts

"scripts": {
        "test": "./node_modules/mocha/bin/mocha -r ts-node/register tests/test.ts"
    },

And after this I can run npm test and everything seems good.

Versions in devDependencies:

"devDependencies": {
    "@types/chai-http": "^4.2.0",
    "@types/expect": "^24.3.0",
    "@types/mocha": "^9.0.0",
    "@types/chai": "^4.2.18",
    "@types/node": "14.14.30",
    "chai": "^4.3.4",
    "mocha": "^9.1.3",
    "ts-node": "^9.1.1",
    "typescript": "^4.4.4"
}

CodePudding user response:

I was unable to find an answer to how to solve it with the command line, but I circumvented the problem by moving the options into package.json

"scripts": {
    "test": "mocha"
},
"mocha": {
    "extension": ["ts"],
    "spec": "test/**/*.ts",
    "require": "ts-node/register"
}

Update: I found the error. I was moving some code without test to having test. The logger was defined in a main.ts file which had some code that ran that was not behind any guard. In fact the error Unsupported Args was my own error message.

The act of referencing a winston logger caused the code in main.ts to run. For some reason this error does not happen now that the mocha options are in package.json even though the logger is still referenced which I find confusing. I am not sure why whether the options are directly in the command line, or they are in the package.json causes such a behavior difference. Regardless, the lesson learned is never reference into your main "running" module.

  • Related