LoginSignup
6
5

More than 3 years have passed since last update.

Node.jsで簡易テストをできるassert.equal()

Last updated at Posted at 2019-11-26

assert.equal()

assert.equalは、アサーションというnode.jsが提供する簡易テストのモジュールです。

const assert = require('assert');
assert.equal(50, 50); //OK
assert.equal(50, "50"); //OK
assert.equal(50, 70); /*AssertionError: 50 == 70 */

//関数と答えの比較もできます
function addition(n) {
  let result = n + 1;
  return result;
}
//第三引数に、エラーが出た場合のエラー表示の設定をできる。
assert.equal(addition(1), 3, `1 + 2の答えは3ですが、計算は${additon(1)}でした`)
//AssertionError: 1 + 2の答えは3ですが、計算は${additon(1)}でした`

assert.deepEqual()

assert.deepEqualは配列オブジェクトの深い比較まで行ってくれます。
例えば、assert.deepEqual([50], [50]);はOKなのに対して、
assert.equal([50], [50]); ではエラーが出てしまいます。
これは、JavaScriptでは配列やオブジェクトを == 演算子で比較した際、同じオブジェクト同士でないとfalseになってしまうからです。

const assert = require('assert');
assert.deepEqual(50, 50); //OK
assert.deepEqual(50, "50"); //OK
assert.deepEqual(50, 70); /*AssertionError: 50 == 70 */
assert.deepEqual([50], [50]); //OK
assert.equal([50], [50]); /*AssertionError: [ 50 ] == [ 50 ] */
6
5
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
6
5