簡體   English   中英

npm chai檢查返回的對象是否具有屬性

[英]npm chai check returned object has property

我正在嘗試用chai檢驗我的Promise。 我的諾言返回了這樣的對象數組:

[
  {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');

您可以嘗試使用Joi (或您的情況下的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函數中獲取固定裝置。 這樣,我正在使用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` 
    );
  });
});

希望能幫助到你

好吧,諾言是異步處理的。 我相信您缺少.then()方法,該方法將返回promise(被拒絕或已實現)。

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

我已經弄清楚了如何避免該錯誤。 比我想象的更簡單,更直接:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM