npm chai 检查返回的对象有 属性

npm chai check returned object has property

我正在尝试用 chai 测试我的 Promise。我承诺 returns 像这样的对象数组:

[
  {id: 1, Location: 'some where'},
  {id: 2, Location: 'over the rainbow'},
]

我不断收到此错误,但我的测试仍然通过:

UnhandledPromiseRejectionWarning: AssertionError: expected [ Array(7) ] to have deep property 'Location'

我的代码:

describe('Function myPromise', () => {
    it(`should returns object with property Location`, () => {
       expect(myPromise(myParams)).to.eventually.have.deep.property('Location');
    });
});

我也试过:

to.eventually.have.deep.property.include('Location');
to.eventually.have.property('Location');
to.eventually.be.an('array').and.have.property('Location');
return expect(myPromise(myParams)).to.eventually.have('Location');

好吧,承诺是异步处理的。我相信您错过了 .then() 方法,其中将 return 承诺(拒绝或履行)。

describe('Function myPromise', () => {
    it(`should returns object with property Location`, () => {
       expect(myPromise(myParams).then(data => data).to.eventually.have.deep.property('Location');
    });
});

您可以尝试在您的情况下使用 Joi (or chai-joi)使模式验证变得非常容易。如果您要进行许多对象模式验证测试,我肯定会尝试这个。

have.deep.property 适用于检查对象,但似乎您检查了数组。

让我用一个简单的例子来说明

const fixtures = [
 {id: 1, Location: 'some where'},
 {id: 2, Location: 'over the rainbow'},
];

// I tested the first element
expect(fixtures[0]).to.have.deep.property('Location'); // passed

如果你想检查每一个元素,你可能需要一个循环。

更新

要使用循环检查每个元素,首先要做的是从promise函数中获取fixtures。这样,我使用的是 async/await,但您也可以使用 promise

describe("Function myPromise", () => {
  it(`should returns object with property Location`, async () => {
    const fixtures = await myPromise(myParams); // get the fixtures first

    // looping and check each element 
    fixtures.forEach(fixture =>
      expect(fixture).to.have.deep.property("Location"); // no need to use `eventually.have.deep` 
    );
  });
});

希望对您有所帮助

我已经找到避免该错误的方法了。比我想象的更简单直接:

describe('Function myPromise', () => {
    it(`should returns object with property Location`, () => {
       myPromise(myParams)
       .then((results) => {
         expect(results).to.be.an('array');
         results.forEach((result) => {
           expect(result).to.have.property('Location');
         });
       });
    });
});