レッスンに戻る

テストのどこが間違っているのでしょうか?

重要度: 5

次のpowテストでは何が間違っていますか?

it("Raises x to the power n", function() {
  let x = 5;

  let result = x;
  assert.equal(pow(x, 1), result);

  result *= x;
  assert.equal(pow(x, 2), result);

  result *= x;
  assert.equal(pow(x, 3), result);
});

追伸 構文的にはこのテストは正しく、合格します。

このテストは、開発者がテストを書くときに陥りやすい誘惑を示しています。

実際にはここには3つのテストがありますが、3つのアサートを持つ単一の関数としてレイアウトされています。

この方法で書く方が簡単な場合もありますが、エラーが発生した場合、何が問題なのかがはるかにわかりにくくなります。

複雑な実行フローの途中でエラーが発生した場合、その時点のデータを把握する必要があります。実際、テストのデバッグを行う必要があります。

このテストを、明確に記述された入力と出力を持つ複数の`it`ブロックに分割したほうがはるかに良いでしょう。

次のようになります。

describe("Raises x to power n", function() {
  it("5 in the power of 1 equals 5", function() {
    assert.equal(pow(5, 1), 5);
  });

  it("5 in the power of 2 equals 25", function() {
    assert.equal(pow(5, 2), 25);
  });

  it("5 in the power of 3 equals 125", function() {
    assert.equal(pow(5, 3), 125);
  });
});

`it`を単独の`describe`と`it`ブロックのグループに置き換えました。これで、何かが失敗した場合、どのようなデータであったかを明確に確認できます。

`it`の代わりに`it.only`を記述することで、単一のテストを分離してスタンドアロンモードで実行することもできます。

describe("Raises x to power n", function() {
  it("5 in the power of 1 equals 5", function() {
    assert.equal(pow(5, 1), 5);
  });

  // Mocha will run only this block
  it.only("5 in the power of 2 equals 25", function() {
    assert.equal(pow(5, 2), 25);
  });

  it("5 in the power of 3 equals 125", function() {
    assert.equal(pow(5, 3), 125);
  });
});