【问题标题】:Sinon - ensure object does not have propertySinon - 确保对象没有属性
【发布时间】:2026-02-16 16:45:02
【问题描述】:

有没有办法和诗乃进行负匹配?具体来说,一个对象没有给定的属性?

谢谢!

【问题讨论】:

    标签: sinon


    【解决方案1】:

    目前没有内置的匹配器。

    Sinon 允许您创建custom matchers,以便您可以创建自己的,这是基于the built-in has matcherdoesNotHave

    import * as sinon from 'sinon';
    
    const doesNotHave = (prop) => sinon.match(function (actual) {
      if(typeof value === "object") {
        return !(prop in actual);
      }
      return actual[prop] === undefined;
    }, "doesNotHave");
    
    test('properties', () => {
      const obj = { foo: 'bar' };
      sinon.assert.match(obj, sinon.match.has('foo'));  // SUCCESS
      sinon.assert.match(obj, doesNotHave('baz'));  // SUCCESS
    })
    

    【讨论】:

    • 应该是typeof actual 而不是typeof value。无论如何,这是一个很好的自定义匹配器示例
    【解决方案2】:

    您不能为此使用sinon,您必须使用chai 之类的东西。

    你会这样做:

    cont { expect } = require("chai");
    
    expect({ foo: true }).to.not.have.keys(['bar']);
    

    https://runkit.com/embed/w9qwrw2ltmpz

    【讨论】:

      【解决方案3】:

      我刚刚意识到可以在对象的形状中指定undefined 来进行检查:

      sinon.assert.match(actual, {
        shouldNotExists: undefined
      });
      

      不完全确定它是否 100% 有效,但似乎可以完成这项工作。

      【讨论】:

      • 在我的测试中,仅当对象具有该属性时才评估为 true