Sinon - 确保对象没有 属性
Sinon - ensure object does not have property
有没有办法和诗乃进行负匹配?具体来说,一个对象没有给定的 属性?
谢谢!
你不能为此使用 sinon
,你必须使用类似 chai
的东西。
你会这样做:
cont { expect } = require("chai");
expect({ foo: true }).to.not.have.keys(['bar']);
目前没有内置的匹配器。
Sinon
允许您创建 custom matchers so you could create your own, here is one for doesNotHave
based on the 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
})
我刚刚意识到可以在对象的形状中指定 undefined
来进行检查:
sinon.assert.match(actual, {
shouldNotExists: undefined
});
不完全确定它是否 100% 有效,但似乎可以做到。
有没有办法和诗乃进行负匹配?具体来说,一个对象没有给定的 属性?
谢谢!
你不能为此使用 sinon
,你必须使用类似 chai
的东西。
你会这样做:
cont { expect } = require("chai");
expect({ foo: true }).to.not.have.keys(['bar']);
目前没有内置的匹配器。
Sinon
允许您创建 custom matchers so you could create your own, here is one for doesNotHave
based on the 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
})
我刚刚意识到可以在对象的形状中指定 undefined
来进行检查:
sinon.assert.match(actual, {
shouldNotExists: undefined
});
不完全确定它是否 100% 有效,但似乎可以做到。