LoginSignup
0
1

More than 3 years have passed since last update.

ts-jest : テストファイルから他のテストファイルをimportするとカバレッジが取得できない

Last updated at Posted at 2020-08-15

はじめに

この記事は、表題の問題について、詳細と解決方法を共有するためのものです。

対象とする読者

この記事はjestおよびTypeScriptでの開発を行っている方を対象としています。それぞれのツールの環境構築などは取り扱いません。

動作環境

  • node.js : v12.18.0
  • TypeScript : v3.9.7
  • ts-jest : v26.1.3

問題の詳細

特定の条件下で、ts-jestのカバレッジが取得できなくなります。

症状

  • テストは成功し、エラーは発生しません。
  • すべてのテスト対象ファイルのカバレッジが0%になります。

再現方法

まず、テストを含むファイルtest1.spec.tstest2.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しています。

解決方法

テストを含むファイルを相互にimportしない

この状態では、test1.spec.tsにimportされているutil.tsがJavaScriptにトランスパイルされ、カバレッジの取得に失敗します。

ts-jestで関数を共有したい場合は、jest.config.jstestMatchオプションの対象とならないファイルに関数を書きます。そして、テストを含むファイルからそれぞれimportします。

上記の再現方法を改善するなら、たとえばcommon.tsというファイルを作成し関数を移します。このファイルにはテストは含まれません。test1.spec.tstest2.spec.tscommon.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();
  ...
});

以上、ありがとうございました。

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