3
1

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 3 years have passed since last update.

Deno.test()の書き方は6つある

Posted at

Denoにはテストランナーが組み込まれています。そのテストランナーで実行されるテストを定義するのがDeno.test()関数です。
公式ドキュメントによるとDeno.test()の書き方は6つあります。

Deno.test()の書き方

Deno.test()の書き方は以下の6つがサポートされています。

// 書き方1
Deno.test({
  name: "<test_name>",
  fn() {
    /* <test_code> */
  }
  // ...(その他のオプション)
});

// 書き方2
Deno.test(function test_name() {
  /* <test_code> */
});

// 書き方3
Deno.test("<test_name>", () => {
  /* <test_code> */
});

// 書き方4
Deno.test({
  // ...(その他のオプション)
}, function test_name() {
  /* <test_code> */
});

// 書き方5
Deno.test("<test_name>", {
  // ...(その他のオプション)
}, () => {
  /* <test_code> */
});

// 書き方6
Deno.test({
  name: "<test_name>",
  // ...(その他のオプション)
}, () => {
  /* <test_code> */
});

どの書き方にも共通しているのが、テスト名を指定する必要があるということです。テスト名を指定しない場合(例えば関数式の代わりに即時間数を指定した時)は、エラーが発生します。

テストのオプションについて

テストにはオブジェクトでオプションを渡すことができます。

Deno.test({
  name: "<test_name>",
  fn() {
    /* <test_code> */
  },
  // 以下はデフォルト値の場合
  ignore: false,
  only: false,
  permissions: "inherit",
  sanitizeExit: true,
  sanitizeOps: true,
  sanitizeResources: true,
});

以下、それぞれのオプションについて解説します。

ignore

ignore: trueを指定するとそのテストは無視されます。
windowsの時だけ無視したい場合は、ignore: Deno.build.os === "windows"のようにします。

only

only: trueを指定したテストが存在する場合、そのテストだけが実行された上でテスト自体は失敗します。(終了コード1)

デバッグ中に特定のテストだけ実行したい場合などにこのオプションを使います。

permissions

テストに許可する権限を指定できます。
permissions: "inherit"(デフォルト)を渡した場合は、コマンドを打った時の権限(--alow-xxx)が引き継がれます。
permissions: "none"を渡した場合は、権限なしで実行されます。
PermissionOptionsObjectを渡しすと、権限を種類別に設定できます。

Deno.test({
  name: "<test_name>",
  fn() {
    /* <test_code> */
  },
  permissions: {
    read: true, // 読み取り権限だけ許可する場合
  },
});

sanitizeOps / sanitizeResources / sanitizeExit

これらはtest sanitizerから発生するエラーを無視するためのオプションです。
詳しくはこちらの記事を参照してください。

テストを入れ子にする方法

テストを入れ子にするには、test steps APIを使います。

Deno.test(async function test_name(t) {
  // この部分は最初に実行される

  await t.step({
    name: "nested test 1",
    fn() {
      // ネストされたテスト
    },
  });

  await t.step({
    name: "nested test 2",
    async fn(t) {
      await t.step({
        name: "nested test 1",
        fn() {
          // 更にネストすることもできる
        },
      });
    },
  });

  // この部分は最後に実行される
});

テスト用の関数の引数にTestContextが渡ってくるので、それに対してt.step()でネストされたテストを定義することができます。

まとめ

  • Deno.test()には書き方が6つある
  • Deno.test()にオプションを渡して挙動を調整できる
  • ネストできる
3
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?