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