0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JEST インストールからテスト実行まで

Last updated at Posted at 2023-03-10

参考URL

こちらJESTのドキュメントになります。
https://jestjs.io/ja/docs/getting-started

JESTをインストール

こちらでJESTのインストールを行なってください。

npm install --save-dev jest

今回は、npmコマンドでインストールしましたが、node.jsをインストールしないとnpmコマンドを使えないので、node.jsをインストールしていない人は、以下を参考にしてください。
https://qiita.com/sefoo0104/items/0653c935ea4a4db9dc2b

実行する

sum.jsを作成して、以下のコードを書きます。

sum.js
//sum関数を作成する。
function sum(a, b) {
  return a + b;
}
//sum.jsファイルをテストファイルで使えるようにする。
module.exports = sum;
sum.test.js
//sum.jsを取得する。
const sum = require('./sum');

test('メモ', () => {
  expect(sum(1, 2)).toBe(3);
});

以下のコードについて説明します。

test('メモ', () => {
  expect(sum(1, 2)).toBe(3);
});

expect

テストしたい値を格納する関数。単体で使うことはほとんどないです。
上のコードだと、sum関数に引数を渡し、関数を実行します。
その結果とこれから説明するMatcherとの結果をテストして、結果を表示します。

Matcher

以上のコードのtoBeというのはMatcher(マッチャー)と呼ばれるものです。
Matcherとは、expectで指定した結果に対して、様々な条件を付けられる機能(関数) になります。
Matcherにはたくさんの種類があります。以下が、Matcherのチートシートになります。参考にしてください。
https://proglearn.com/2019/11/30/jest-%e3%83%81%e3%83%bc%e3%83%88%e3%82%b7%e3%83%bc%e3%83%88-javascript%e3%81%a7%e3%83%86%e3%82%b9%e3%83%88%e3%82%92%e6%9b%b8%e3%81%93%e3%81%86/

例①

以下のコードは、文字列(Christoph)にstopという文字列が入っていれば成功。入っていなければ失敗。というテストコードになります。

test('but there is a "stop" in Christoph', () => {
  expect('Christoph').toMatch(/stop/);
});

結果は成功になります。

例②

こちらは"team"の中にI文字が含まれていなければテスト成功。含まれていたら失敗。というテストコードになっています。

test('there is no I in team', () => {
  expect('team').not.toMatch(/I/);
});

こちらも「team」という文字列に「I」は入っていないので、結果は成功します。

以上になります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?