0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ts-mocha + typescript 環境では期待値どおりにテストを実行できない

Posted at

環境

  • typescript : 5.1.6
  • ts-mocha : 10.2.0
  • ts-node : 10.0.0
  • tsconfig-paths: 4.2.0

期待値(何がしたいのか)

  • mocha + chai 環境でtypescriptで書かれたコードのテストがしたい
  • tsconfigに割当しているpathsもテストコード内で認識してほしい

事象(実際はどうなるか)

ts-mocha等、ts-nodeに依存しているpackageを実行すると、以下のエラーになる。

bash
# tsconfig paths を認識させる場合
> ts-mocha --paths -p ./tsconfig.json

[ERROR] The "path" argument must be of type string. Received an instance of Array
bash
# tsconfig paths は無視する場合
> ts-mocha -p ./tsconfig.json

✖ ERROR: TypeError: value.replace is not a function
# ( ...以下略... )

結論(解決策)

一旦tsc --showConfigで、tscが実際に読み込んでいるtsconfigを出力してから、その出力されたtsconfigを参照するように指定する

bash
# tsconfig.tsnode.json を一旦出力
$ tsc --project=./tsconfig.json --showConfig > tsconfig.tsnode.json

# 出力した tsconfig.tsnode.json を使う
# tsconfig paths を認識させる場合
$ ts-mocha --paths --project=./tsconfig.tsnode.json
bash
# tsconfig.tsnode.json を一旦出力
$ tsc --project=./tsconfig.json --showConfig > tsconfig.tsnode.json

# 出力した tsconfig.tsnode.json を使う
# tsconfig paths は無視する場合
$ ts-mocha --project=./tsconfig.tsnode.json

npm script の設定例

package.json
{
  "script":{
    "pretest":"tsc -p ./tsconfig.json --showConfig > tsconfig.tsnode.json",
    "test":"ts-mocha --paths -p ./tsconfig.tsnode.json"
  }
}
bash
# テストコマンドを実行するだけで済む
npm run test

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?