我希望有一种更简单的方法来检查对象是否具有空数组

I expect there is an easier way top check for an object to have an empty array

我正在使用 chai 和 sinon 编写一些测试。

我有这个对象:

{
    payload: {
        foo: 'bar',
        bar: []
    },
    type: 'FOO:BAR'
}

并且我想写一个期望,即对象包含一个名为 bar 的 属性,它是一个空对象。

我有这个 foo:

expect(myObject).to.have.property('foo', 'bar')

简洁明了。将它与这个相当长的期望进行比较:

expect(myObject).to.have.property('bar').that.is.an('array').with.property('length', 0)

我这样写是因为如果我使用 property('bar', []),属性 会通过引用进行比较,并且基于此 cheatcheet 中的示例(请参阅 属性 节)。

有没有更简洁的方式来写这个期望?

因为您已经在使用 sinon,您可以使用 sinon.assert.match 来测试:

the value...be not null or undefined and have at least the same properties as expectation

这会检查 obj 是否包含 至少 payload 以及 foobar 的预期值:

const sinon = require('sinon');

const obj = {
  payload: {
    foo: 'bar',
    bar: []
  },
  type: 'FOO:BAR'
};

it('should match', () => {
  sinon.assert.match(obj, {
    payload: {
      foo: 'bar',
      bar: []
    }
  });  // Success!
});

另一个选项(看起来是 @Xufox 在评论中首先建议的)是 .eql 来自 chai 其中:

Asserts that the target is deeply equal to the given obj

这会检查 obj.payload 是否等于 { foo: 'bar', bar: [] }:

const expect = require('chai').expect;

const obj = {
  payload: {
    foo: 'bar',
    bar: []
  },
  type: 'FOO:BAR'
};

it('should match', () => {
  expect(obj.payload).to.eql({
    foo: 'bar',
    bar: []
  });  // Success!
});