[英]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');
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.