比较两个对象 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个错误。一个是 response 中的 key1 是一个 string 并且我期待一个 array 和另一个可能是 response 有一个非预期的密钥 (key4)。

这可能吗?谢谢!!

您需要使用自己的逻辑来测试您要查找的内容。几乎有两件事需要测试——类型匹配,以及响应中需要匹配您的对象的属性数量。我定义了两个函数,testTypesEqual(returns 如果类型匹配则为真)和 testPropertiesMatch(returns 如果响应具有与您的对象相同的属性则为真)。您将需要在测试中使用这些(或根据您的具体需要使用这些的变体)。可以在此处找到完整示例 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");

很明显,现在我已经在你的单元测试中引入了新的和重要的逻辑,这个答案的唯一目的是向你展示如何去做,而不是建议你从陌生人那里获取复杂的逻辑并坚持下去整个单元测试:).