提问者:小点点

如何使用Chai或vanilla javascript近似比较JSON对象文本


考虑JSON对象文本的预期实际值:

        let expectedResult = {
                [0.9272952180016122, 1.1760052070951352, 1.0808390005411683],
                [1.2870022175865687, 0.8097835725701669,  1.240498971965643],
                [1.3494818844471053, 1.014197008784674,  1.3894765523934063]
            ],
            'spectrum': [
                [ 5, 13, 17],
                [25, 29, 37],
                [41, 53, 61]
            ]
        };

        let actualResult = {
                [0.9272952180016122, 1.1760052070951352, 1.0808390005411683],
                [1.2870022175865687, 0.8097835725701669,  1.240498971965643],
                [1.3494818844471053, 1.014197008784674,  1.3894765523934063]
            ],
            'spectrum': [
                [ 5, 13, 17],
                [25, 29, 37],
                [41, 53, 61]
            ]
        };

第二个条目不同:1.17600520709513521.176005207095135。 在javascript或Chai中是否有任何结构来处理这种比较?

以下内容不起作用,因为它最终是一个对象比较

    chai.expect(actualResult).to.be.closeTo(expectedResult);

AssertionError:expectedResult{Object(real,imag,。。。)}为数字


共1个答案

匿名用户

这个函数显然是为chai5指定的。 https://github.com/chaijs/chai/issues/644。

计划是在Chai 5中有这种行为。 现在欢迎您制作接受Sinon匹配器的插件--但请注意,到Chai5问世时,它可能已经过时了

同时,这里有一个解决办法

最后我把@Vaskevich方法作为一个插件来实现。 它甚至替换了这个关于存根被调用的潜在混淆的文本。 这是:

chai.use((_chai, utils) => {
  chai.Assertion.addMethod('matchEql', function fn(expectedMatch) {
    const subject = utils.flag(this, 'object');
    const stub = sinon.stub();
    stub(subject);
    try {
      sinon.assert.calledWithMatch(stub, expectedMatch);
    } catch (error) {
      error.name = 'MatchAssertionError';
      error.message = error.message.replace(
        /^expected stub to be called with match/,
        `expected ${utils.objDisplay(subject)} to match`
      );
      throw error;
    }
  });
});