Skip to content

Jest

Jestの導入

ブラウザからの動作確認はいったん置いておいて、コマンドライン実行で動くものを目指す。

どうせなら自動テストも動かしながらやっていきたい。

JavaScriptのテストフレームワークは、Jest · 🃏 Delightful JavaScript Testingが主流らしいので、それに乗っかる。

Typescriptでの単体テストの書き方(Jest) | スターフィールド株式会社を見ながらインストール。

$ npm install --save-dev jest typescript ts-jest @types/jest
$ npx ts-jest config:init
$ code jest.config.js
$ code package.json
$ npm run test
ts-jest[versions] (WARN) Version 28.0.3 of jest installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version (>=27.0.0 <28.0.0-0). Please do not report issues in ts-jest if you are using unsupported versions.
ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.

jestとts-jestのバージョンが不一致らしい。

Read more

rewireでjest

テストのために関数exportしないといけないの、チョット気持ち悪いので、解決策を探ってみる。

jhnns/rewire: Easy monkey-patching for node.js unit testsが一般的らしい。

$ npm install -D rewire @types/rewire

テストコードのimportを修正

import rewire from 'rewire';

const __local__ = rewire('./mdmml.ts');
const atoi = __local__.__get__('atoi')

テスト実行

$ npm test

> mdmml_js@1.0.0 test
> jest

 FAIL  src/mdmml.test.ts
  ● Test suite failed to run

    /home/umemak/workspace/mdmml_js/src/mdmml.ts:8
        Tracks: Track[] = [];
        

    SyntaxError: Unexpected identifier

      at Object.load (node_modules/rewire/lib/moduleEnv.js:57:18)
      at internalRewire (node_modules/rewire/lib/rewire.js:49:15)
      at rewire (node_modules/rewire/lib/index.js:11:12)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.01 s
Ran all test suites.

関係ないところでエラーになるようになってしまった。。

Read more