为什么 sinon.assert.match(actual, expected) 在 actual 和 expected 是相同的字符串值时会抛出 AssertError?

Why sinon.assert.match(actual, expected) would throw AssertError when both actual and expected are identical string values?

我有 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.

更正了它

因为测试比较参考,所以失败了。该代码使用 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);
})

希望对您有所帮助