當我使用不同的節點版本運行以下陳述句時,我看到斷言結果有所不同。我正在使用斷言通過的 v10.15.1。但是 v14.18.1 中的相同代碼會引發錯誤。
const assert = require('assert')
var err = new Error('some error');
var d = [{
'error':[err]
}]
var expected = [{
'error':[{}]
}]
assert.deepEqual(d,expected)
錯誤如下:
assert.js:118
throw new AssertionError(obj);
^
AssertionError [ERR_ASSERTION]: Expected values to be loosely deep-equal:
[
{
error: [
Error: some error
at Object.<anonymous> (/Users/username/Desktop/repos/temp_files/test.js:2:11)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as r...
should loosely deep-equal
[
{
error: [
[]
]
}
]
at Object.<anonymous> (/Users/username/Desktop/repos/temp_files/test.js:9:8)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47 {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: [
{
error: [
Error: some error
at Object.<anonymous> (/Users/username/Desktop/repos/temp_files/test.js:2:11)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
]
}
],
expected: [ { error: [ [] ] } ],
operator: 'deepEqual'
}
我參考了這兩個版本的檔案,但沒有發現它有用。
v10
v14
我當然理解錯誤物件在一個中是空的,但在另一個中不是。但是找不到 v10 忽略它的原因以及后來發生了什么變化,因此現在捕獲了錯誤
uj5u.com熱心網友回復:
assert.deepEqual在 Node.js 12 中,這個pull request的行為發生了變化。改變背后的部分動機是要求將松散的平等比較與嚴格的平等比較結合起來,后者的行為從一開始就更容易預測。結果,斷言
assert.deepEqual(new Error('test'), { });
在 Node.js < 12 中通過,但在 Node.js 12 及更高版本中失敗。
簡單的解釋是Errors 是沒有自己可列舉屬性的物件。在舊版本的 Node.js 中,anError和空物件字面量 ( { }) 都是沒有自己可列舉屬性的物件這一事實足以讓兩者進行松散相等的比較。Node.js 12 中的行為發生了變化,其中狀態檔案deepEqual:
Error總是比較名稱和訊息,即使它們不是可列舉的屬性。
當然,這不會以任何方式使您觀察到的變化變得明顯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/421461.html
標籤:
