準備
依存パッケージをインストール
npm i -D coffeescript typescript jest @types/jest ts-jest
テスト前にCoffeeScriptを変換するのに必要なファイルを用意
こんな感じでpackage.json
と同じ階層に置いておく。
coffee-preprocessor.js
const coffee = require('coffeescript');
module.exports = {
process: (src, path) => {
if (coffee.helpers.isCoffee(path)) {
return coffee.compile(src, {bare: true});
}
return src;
}
};
設定
package.json
のjest
はこんな感じで。
package.json
{
"jest": {
"transform": {
"^.+\\.coffee$": "<rootDir>/coffee-preprocessor.js",
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "/__tests__/.*\\.coffee$",
"moduleFileExtensions": [
"js",
"jsx",
"json",
"coffee",
"ts",
"tsx",
]
}
}
これで__tests__/test.coffee
みたいなファイルが対象ファイルになりました。.coffee
の中で.ts
ファイルを読み込んだりする想定なので、TypeScriptでJestで書くのと同じ設定も必要になります。
テスト
ディレクトリ構造はこんな感じです。
tree -I node_modules
# .
# ├── coffee-preprocessor.js
# ├── package.json
# ├── package-lock.json
# ├── src
# │ ├── __tests__
# │ │ └── add.coffee
# │ └── add.ts
# └── tsconfig.json
適当にadd.ts
とadd.coffee
を用意します。
add.ts
export function add<T extends number>(a: T, b: T): T {
const c = a + b;
return c as T;
}
__tests__/add.coffee
{add} = require '../add'
test 'add', ->
expect add(1, 1)
.toBe 2
実行
npx jest
# PASS src/__tests__/add.coffee
# ✓ add (5ms)
#
# Test Suites: 1 passed, 1 total
# Tests: 1 passed, 1 total
# Snapshots: 0 total
# Time: 3.351s
# Ran all test suites.
# ✨ Done in 4.30s.
通りました🎉