如何在Chai断言错误中查看[Object] [Object]的内部详情?
如何查看断言错误中[Object]的具体内容?
问题场景
编写的前端测试代码如下:
let resultRedirects = { redirects: { fromPaths: [ { path: '/a-good/path', type: 302 }, { path: '/goodpath/Rocky%20Mountain%20PBS-HD,%20Create%20and%20V-me.', type: 301 } ], toPath: '/shows/default' } }; let someFunc = sinon.stub(); let wrapper = shallow(<Settings {...props} />); wrapper.instance().someFunc2({ target: { value: '302' } }, 0); expect(someFunc).to.have.been.calledWith(resultRedirects);
对应的changeRedirectType(即测试中的someFunc2)函数代码:
changeRedirectType = (e, index) => { const { redirects, redirects: { fromPaths }, path } = this.props; let redirectsFromPaths = [...fromPaths]; redirectsFromPaths[index].type = parseInt(e.target.value); changeSettings({ redirects: { ...redirects, toPath: path, fromPaths: redirectsFromPaths } }); };
执行测试后得到断言错误:
AssertionError: expected stub to have been called with arguments { redirects: { fromPaths: [ [Object], [Object] ], toPath: '/shows/default' } } { redirects: { fromPaths: [ [Object], [Object] ], toPath: '/shows/default' } }
需要查看错误信息中[Object]的内部具体内容。
解决方法
用
JSON.stringify()打印完整结构
在断言前添加日志,把实际调用参数和预期结果转成格式化的JSON字符串输出:// 打印someFunc的第一个调用参数 console.log(JSON.stringify(someFunc.firstCall.args[0], null, 2)); // 打印预期的resultRedirects console.log(JSON.stringify(resultRedirects, null, 2));运行测试后就能在控制台看到展开的完整对象,直接对比差异。
调整测试框架的输出截断设置
如果使用Chai测试框架,在测试文件开头添加配置禁用输出截断:require('chai').config.truncateThreshold = 0;这样错误信息会直接展开所有对象属性,不再显示
[Object]。在目标函数中打印中间值
在changeRedirectType函数修改完redirectsFromPaths后,临时添加日志:console.log(JSON.stringify(redirectsFromPaths, null, 2));直接查看函数处理后的数组结构,确认是否和预期一致。
内容的提问来源于stack exchange,提问作者Andrei Lupuleasa
相关产品推荐
相关产品推荐

