check chai as promised on multiple properties object

我的未来我决定 提交于 2019-12-12 04:54:31

问题


hello I have a method which returns me data along with URL , so return object has url and body as two properties.

  return new Promise(function(resolve,reject)
    {
      request(url, function (error, response, body) {
        if(error)
              reject(error);
          else
          {
              if(response.statusCode ==200)
                    resolve( { "url" :url , "body" : body});
                else
                    reject("error while getting response from " + url);
          }
      });

    });

How should I test this in Chai- as promised

it works for 1 property.

it("get data from correct url", function(){
   return expect (httphelper.getWebPageContent(config.WebUrl))
   .to.eventually.have.property('url')
});

if I include other property it searches inside previous property.

it("get data from correct url", function(){
   return expect (httphelper.getWebPageContent(config.WebUrl))
   .to.eventually.have.property('url')
   .and.to.have.property('body')
});

AssertionError: expected 'http://www.jsondiff.com/' to have property 'body'

where I'm going wrong?


回答1:


Create an object with the expected properties :

const expected = {
    url: "expected url",
    body: "expected body"
};

Then ensure the result include this properties with :

return expect(httphelper.getWebPageContent(config.WebUrl))
.fulfilled.and.eventually.include(expected);



回答2:


First on your problem; the check for body happens on the object url, not on the original object (the chaining is like jQuery chaining), and as the error message says, the string http://www.jsondiff.com/ does not have a property of body.

Given that, one solution would be to get the returned object and then do two separate checks:

it('get data from correct url', async () => {
  const res = await httphelper.getWebPageContent(config.WebUrl));

  expect(res).to.have.property('url');
  expect(res).to.have.property('body');
});

or if you want to stick with chai-as-promised:

it('get data from correct url', async () => {
  const res = httphelper.getWebPageContent(config.WebUrl));

  expect(res).to.be.fulfilled
  .then(() => {
    expect(res).to.have.property('url');
    expect(res).to.have.property('body');
  });
});

Another solution would be to grab the object's keys and then use the members() function to see if the list contains your properties:

it('get data from correct url', async () => {
  const res = await httphelper.getWebPageContent(config.WebUrl));

  expect(Object.keys(res)).to.have.members(['url', 'body']);
});


来源:https://stackoverflow.com/questions/46064455/check-chai-as-promised-on-multiple-properties-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!