• Node.js Video Tutorials

Node.js - assert.notEqual() 函式



Node.js assert.notEqual() 函式使用 != 運算子測試實際引數和預期引數。如果值相等,則函式將丟擲 AssertionError 異常。如果值不相等,則函式不會返回任何輸出。

此函式與assert.notStrictEqual() 函式幾乎相同。

語法

以下是Node.js assert.notEqual() 函式的語法:

assert.notEqual(actual, expected[, message]);

引數

此函式接受三個引數,如下所述。

  • actual − (必填) 此引數中傳遞的值將被評估。值可以是任何型別。

  • expected − (必填) 此引數中傳遞的值將與actual 值進行比較。值可以是任何型別。

  • message − (可選) 可以將字串或 Error 型別作為輸入傳遞給此引數。

返回值

如果actualexpected 值匹配,則此函式將在終端返回 AssertionError 異常。

示例

在下面的示例中,我們將兩個不同的整數傳遞給Node.js assert.notEqual() 函式的actualexpected 引數。

const assert = require('assert');

var num1 = 5;
var num2 = 6;

assert.notEqual(num1, num2, "Both values are Not EQUAL");

輸出

由於兩個輸入引數的結果不同,因此函式不會向輸出丟擲 AssertionError 異常。

// Returns nothing

示例

在下面的示例中,我們將兩個相同的整數傳遞給函式的actualexpected 引數。

const assert = require('assert');

var int1 = 65;
var int2 = 65;

assert.notEqual(int1, int2, "Both integers are EQUAL");

輸出

由於兩個輸入引數的結果相同,因此函式將丟擲 AssertionError 異常以及message 引數中的文字。

assert.js:79
   throw new AssertionError(obj);
   ^
   
AssertionError [ERR_ASSERTION]: Both integers are EQUAL
   at Object.<anonymous> (/home/cg/root/639c38b0b0aed/main.js:6:8)
   at Module._compile (internal/modules/cjs/loader.js:702:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
   at Module.load (internal/modules/cjs/loader.js:612:32)
   at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
   at Function.Module._load (internal/modules/cjs/loader.js:543:3)
   at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
   at startup (internal/bootstrap/node.js:238:19)
   at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)

示例

在下面的示例中,我們建立了兩個具有不同屬性的物件。然後我們將這兩個物件作為actualexpected 傳遞給函式,並將文字傳遞給message 引數。

const assert = require('assert');
var obj1 = {
   Name : 'Krishna',
   Age : 28
};

var obj2 = {
   Name : 'Kasyap',
   Age : 30
};

assert.notEqual(obj1, obj2, "Both the objects are NOT EQUAL");

輸出

由於實際結果和預期結果不同,因此在編譯和執行程式碼時,函式不會丟擲 AssertionError 異常。

// Returns nothing

示例

在下面的示例中,我們將兩個相同的字串作為輸入傳遞給actualexpected 引數。

const assert = require('assert');

assert.notEqual('Tutorialspoint', 'Tutorialspoint', "Both the strings are EQUAL");

輸出

由於實際結果和預期結果相同,因此在編譯和執行程式碼時,函式將向輸出丟擲 AssertionError 異常。

assert.js:79
   throw new AssertionError(obj);
   ^
   
AssertionError [ERR_ASSERTION]: Both the strings are EQUAL
   at Object.<anonymous> (/home/cg/root/639c38b0b0aed/main.js:3:8)
   at Module._compile (internal/modules/cjs/loader.js:702:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
   at Module.load (internal/modules/cjs/loader.js:612:32)at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
   at Function.Module._load (internal/modules/cjs/loader.js:543:3)
   at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
   at startup (internal/bootstrap/node.js:238:19)
   at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)
nodejs_assert_module.htm
廣告