诗乃 - 确保物品没有财产

问题描述 投票:1回答:3

Sinon有没有办法让负面比赛?具体来说,一个对象没有给定的属性?

谢谢!

sinon
3个回答
2
投票

目前没有内置的匹配器。

Sinon允许你创建custom matchers所以你可以创建自己的,这里是基于doesNotHavethe built-in has matcher

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
})

1
投票

你不能使用sinon,你必须使用像chai这样的东西。

你会这样做:

cont { expect } = require("chai");

expect({ foo: true }).to.not.have.keys(['bar']);

https://runkit.com/embed/w9qwrw2ltmpz


0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.