LoginSignup
1
0

More than 5 years have passed since last update.

TypeScript のテストを Jest と CoffeeScript で書く

Posted at

準備

依存パッケージをインストール

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.jsonjestはこんな感じで。

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.tsadd.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.

通りました🎉

1
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
1
0