[英]Comparing Two Objects QUnit Javascript
我需要比較兩個對象的屬性和屬性類型,而不只是值的類型。
所以我有var a = {key1 : [], key2: { key3 : '' } }
我想將其與我從Web服務調用中得到的另一個對象進行比較。
在這種情況下, response
等於{key1 : '', key2: { key3 : '' }, key4: 1 }
我嘗試做propEqual()
assert.propEqual(response, a, "They are the same!");
我相信這是對特性的測試,但同時也在測試特性的值。 我不在乎值,我只想測試整體結構和類型。
因此,給出上述數據示例,測試應拋出2個錯誤。 一種可能是, response
的key1
是一個字符串 ,我正在期待一個數組 ,另一種可能是, response
包含了一個不期望的鍵( key4 )。
這可能嗎? 謝謝!!
您將需要使用自己的邏輯來測試所需的內容。 有兩件事要測試-類型匹配和響應中需要匹配對象的屬性數量。 我定義了兩個函數, testTypesEqual
(如果類型匹配, testPropertiesMatch
返回true)和testPropertiesMatch
(如果response與對象具有相同的屬性,則返回true)。 您將需要在測試中使用這些(或根據您的實際需求而定)。 完整的示例可以在http://jsfiddle.net/17sb921s/中找到。
//Tests that the response object contains the same properties
function testPropertiesMatch(yours, response){
//If property count doesn't match, test failed
if(Object.keys(yours).length !== Object.keys(response).length){
return false;
}
//Loop through each property in your obj, and make sure
//the resposne also has it.
for(var prop in yours){
if(!response.hasOwnProperty(prop)){
//fail if response is missing a property found in your object
return false;
}
}
return true;
}
//Test that property types are equal
function testTypesEqual(yours, response){
return typeof(yours) === typeof(response)
}
您必須為每個要檢查類型不匹配的屬性編寫一個assert.ok
。 最后,您將只有一個assert.ok
檢查response
中的屬性是否與對象中的屬性匹配。
例:
//fails for key1
assert.ok(testTypesEqual(a.key1, response.key1), "Will fail - key1 property types do not match");
//fails - response contains additional property
assert.ok(testPropertiesMatch(a, response), "Additional Properties - Fail due to additional prop in Response");
顯然,現在我已經在您的單元測試中引入了新的,非平凡的邏輯,此答案的唯一目的是向您展示如何做,而不是建議您從陌生人那里學習復雜的邏輯,並堅持在整個單元測試中堅持下去:)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.