我正在尝试创建一个断言方法,使有问题的对象只包含标量值(即字符串或数字等简单值)。可以使用JSON.stringify()。
示例PASSED:
var expected = {foo: 5, bar: 6};
var actual = {foo: 5, bar: 6}
objectAssert(actual, expected, 'detects that two objects are equal');
// console output:
// passed
示例失败:
var expected = {foo: 6, bar: 5};
var actual = {foo: 5, bar: 6}
objectAssert(actual, expected, 'detects that two objects are equal');
// console output:
// FAILED [my test] Expected {"foo":6,"bar":5}, but got {"foo":5,"bar":6}
到目前为止,这是我的功能:
function objectAssert(actual, expected, testName) {
if(actual !== expected){
console.error( "FAIL [" + testName + "] Expected \"" + expected + ", \" but got \"" + actual + "\"");
} else {
console.info( "SUCCESS [" + testName + "]");
}
}
知道我在这里缺少什么吗?
答案 0 :(得分:0)
使用!==
来比较对象是错误的。我建议的是,就像你在问题中提到的那样,使用JSON.stringify
比较两个对象。
示例:
function objectAssert(actual, expected, testName) {
_actual = JSON.stringify(actual);
_expected = JSON.stringify(expected);
if(_actual != _expected)
console.error( "FAIL [" + testName + "] Expected \"" + expected + ", \" but got \"" + actual + "\"");
else
console.info( "SUCCESS [" + testName + "]");
}
答案 1 :(得分:0)
您可以比较json字符串对象:
if(JSON.stringify(actual) !== JSON.stringify(expected)){
console.error( "FAIL [" + testName + "] Expected \"" + JSON.stringify(expected) + ", \" but got \"" + JSON.stringify(actual) + "\"");
} else {
console.info( "SUCCESS [" + testName + "]");
}