比较两个对象 QUnit Javascript

问题描述 投票:0回答:1

我需要比较两个对象的属性和属性类型,而不是值,只是类型。

所以我有

var a = {key1 : [], key2: { key3 : '' } }

我想将其与我从网络服务调用中返回的另一个对象进行比较。

在这种情况下,

response
等于
{key1 : '', key2: { key3 : '' }, key4: 1 }

我尝试做propEqual()

 assert.propEqual(response, a, "They are the same!");

这确实是对我相信的属性的测试,但它也在测试属性的价值。我不关心值,我只想测试整体结构和类型。

因此给出上述数据示例,测试应该抛出 2 个错误。一个是,

key1
中的
response
是一个字符串,我期待一个数组,另一个是
response
有一个不符合预期的键(key4)。

这可能吗?谢谢!!

javascript unit-testing qunit
1个回答
1
投票

您需要使用自己的逻辑来测试您正在寻找的内容。几乎有两件事需要测试——类型匹配,以及响应中需要与对象匹配的属性数量。 我定义了两个函数,

testTypesEqual
(如果类型匹配则返回 true)和
testPropertiesMatch
(如果响应与对象具有相同的属性则返回 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");

显然现在我已经在您的单元测试中引入了新的且重要的逻辑,这个答案的唯一目的是向您展示如何做到这一点,而不是建议您从陌生人那里获取复杂的逻辑并将其粘贴到您的整个单元中测试:)。

© www.soinside.com 2019 - 2024. All rights reserved.