【问题标题】:Why sinon.assert.match(actual, expected) would throw AssertError when both actual and expected are identical string values?为什么当实际和预期都是相同的字符串值时 sinon.assert.match(actual, expected) 会抛出 AssertError ?
【发布时间】:2020-03-16 17:30:09
【问题描述】:

我有mocha, chai and sinon Javascript 测试框架和库可用于我继承的应用程序。我对所有 ^ 都是新手,我一直在阅读他们的 APIs 以了解如何正确使用它们。

这是我要验证的 Javascript 对象。如果预期的name 属性缺失,验证器将抛出UsageError: name property is missing

// person object
const person = { name: 'peter' }

// validate method of exported validator JS component
async validate(person) {
    const { name } = person;
    const promises = [];
    if (typeof name !== object) { throw new UsageError('name property is missing'); }
    ...
    else { promises.push(fooService(name)); }
    try {
        await Promise.all(promises);
    } catch (error) { throw (error); }
}

// unit test in sinon
describe('Validate person', async function() {    
it('should throw error not find name property', async function() {
  const person = { 'foo': '1234 somewhere' };
 try {
  await validator.validate(person);
 } catch(error) {      
  sinon.assert.match(error, 'name property is missing');
 }              
});

这是async + await 的代码,我知道sinon 很合适,然后当我执行单元测试时,我什至对以下错误消息感到困惑:

AssertError: expected value to match
expected = UsageError: name property is missing
actual = UsageError: name property is missing

我认为actualexpected 在字符串中的输出相同,但我不明白为什么我得到AssertError。如果有人可以向我解释我做错了什么并指导我以正确的方式实施此单元测试,我将不胜感激。太棒了!

[更新]

抱歉,我意识到我在发布的示例测试中给出了错误的示例。我通过 person object does not contain name property 纠正了它。

【问题讨论】:

    标签: javascript sinon


    【解决方案1】:

    它失败了,因为测试比较了参考。该代码使用new 语句创建新引用,例如new UsageError

    一个例子:

    let expect = require('chai').expect;
    
    it('checks equality' ,function() {
      const actual = new Error('name property is missing');
      const expected = new Error('name property is missing');
    
      expect(actual).to.equal(expected);
    })
    

    上面的代码会给出输出

    // output
    AssertionError: expected [Error: name property is missing] to equal [Error: name property is missing]
          + expected - actual
    

    解决方案也许你可以通过访问message属性来比较消息

    it('checks equality' ,function() {
      ...
    
      expect(actual.message).to.equal(expected.message);
    })
    
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 2011-07-01
      • 2010-09-30
      • 2014-08-14
      • 2021-07-03
      • 2014-11-24
      • 1970-01-01
      相关资源
      最近更新 更多