LoginSignup
0
0

タグ付きテンプレートを使ったJest eachの書き方

Posted at

Jestのテストを書いていて、便利だと思ったので、紹介です。

テンプレートリテラルとは

テンプレートリテラルとは、バッククォート区切られたリテラルです。

これは、なんとなくわかります。

console.log(`hoge hoge`);
// => hoge hoge
console.log(`hoge 
hoge`);
// => 
// hoge 
// hoge
hoge = 'hoge'
console.log(`hoge ${hoge} hoge`);
// => hoge hoge hoge

タグ付きテンプレートとは

タグつきテンプレートリテラルは、リテラルから任意のテキストセグメントの配列と、任意の置換の値を引数として関数(タグ関数)を呼び出します。

いまいちわからなかったので、例を書きます。

const val1 = "TaggedTemplateLiteral"
const val2 = "amazing"

function WhatTaggedTemplateLiteral(strings, ...values) {
    console.log(strings);
    console.log(values);
}

WhatTaggedTemplateLiteral`I think ${val1} are ${val2}.`
// => ['I think ', ' are ', '.', raw: Array(3)]
// => ['TaggedTemplateLiteral', 'amazing']

すごく例が微妙ですが、なにがわかるというと
stringsの中には、${}で区切られたものが配列になっていて、
valuesの中には、${}の中身が配列になっています。

タグ付きテンプレートを利用したJest each

上記で説明したタグ付きテンプレートを使って、Jest eachを書くと👇

test.each`
amount              | taxRate              | taxIncludeAmount    | explanation
${new Decimal(100)} | ${new Decimal(0.1)}  | ${new Decimal(110)} | ${`消費税10%`}
${new Decimal(100)} | ${new Decimal(0.08)} | ${new Decimal(108)} | ${`消費税8%`}
${new Decimal(100)} | ${new Decimal(0.05)} | ${new Decimal(105)} | ${`消費税5%`}
`(`$explanation の計算`, ({ amount, taxRate, taxIncludeAmount, explanation }) => {
        expect(amount * (1 + taxRate)).equals(taxIncludeAmount)).toBeTruthy();
});

このように同じような値の計算を繰り返しテストや閾値付近のテストでは、タグ付きテンプレートを使って書くと可読性が上がるので良いと思いました。

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