繁体   English   中英

比较两个对象QUnit Javascript

[英]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个错误。 一种可能是, responsekey1是一个字符串 ,我正在期待一个数组 ,另一种可能是, 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM