我正在尝试使用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');
答案 0 :(得分:1)
答案 1 :(得分:1)
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`
);
});
});
希望有帮助
答案 2 :(得分:0)
好的承诺是异步处理的。我相信您缺少.then()
方法,在该方法中将返回promise(被拒绝或已实现)。
describe('Function myPromise', () => {
it(`should returns object with property Location`, () => {
expect(myPromise(myParams).then(data => data).to.eventually.have.deep.property('Location');
});
});
答案 3 :(得分:0)
我已经弄清楚了如何避免该错误。比我想象的更简单直接:
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');
});
});
});
});