检查chai在多个属性对象上的承诺

时间:2017-09-05 23:01:32

标签: javascript mocha chai-as-promised

你好我有一个方法可以将数据和URL一起返回给我,因此返回对象将url和body作为两个属性。

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

    });

我应该如何在Chai-中承诺

进行测试

适用于1个属性。

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

如果我包含其他属性,则会在之前的属性中搜索。

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

AssertionError:预期'http://www.jsondiff.com/'拥有属性'body'

我哪里出错了?

2 个答案:

答案 0 :(得分:1)

创建具有预期属性的对象:

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

然后确保结果包含以下属性:

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

答案 1 :(得分:0)

首先关注你的问题;检查body发生在对象url上,而不是原始对象上(链接就像jQuery链接),并且正如错误消息所示,字符串http://www.jsondiff.com/没有body的财产。

鉴于此,一种解决方案是获取返回的对象,然后进行两次单独的检查:

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

或者如果你想坚持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');
  });
});

另一个解决方案是获取对象的,然后使用members()函数查看列表是否包含您的属性:

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

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