この記事は、表題の問題について、詳細と解決方法を共有するためのものです。
この記事はjestおよびTypeScriptでの開発を行っている方を対象としています。それぞれのツールの環境構築などは取り扱いません。
特定の条件下で、ts-jestのカバレッジが取得できなくなります。
まず、テストを含むファイルtest1.spec.ts
とtest2.spec.ts
を作成します。
▼test1.spec.ts
import { util } from "../src/util"
test("test1", () => {
supportTest();
...
});
export function supportTest():void{
...
}
▼test2.spec.ts
import { util } from "../src/util";
import { supportTest } from "./test1.spec";
test("test2", () => {
supportTest();
...
});
test1.spec.ts
にはexportされた関数supportTest
があります。test2.spec.ts
ではsupportTest
をimportしています。
この状態では、test1.spec.ts
にimportされているutil.ts
がJavaScriptにトランスパイルされ、カバレッジの取得に失敗します。
ts-jestで関数を共有したい場合は、jest.config.jsのtestMatchオプションの対象とならないファイルに関数を書きます。そして、テストを含むファイルからそれぞれimportします。
上記の再現方法を改善するなら、たとえばcommon.ts
というファイルを作成し関数を移します。このファイルにはテストは含まれません。test1.spec.ts
とtest2.spec.ts
はcommon.ts
から関数をimportします。
▼common.ts
export function supportTest():void{
...
}
▼test1.spec.ts
import { util } from "../src/util"
import { supportTest } from "./common";
test("test1", () => {
supportTest();
...
});
▼test2.spec.ts
import { util } from "../src/util";
import { supportTest } from "./common";
test("test2", () => {
supportTest();
...
});
以上、ありがとうございました。