如何使用 Chai 断言查看 Promise 是否包含特定数据

How to see if a Promise contains specific data using Chai assertions

我已经开始使用 Chakram Rest API 测试框架,它利用了 Chai 断言库。在我下面的代码中 Chakram.get returns 一个 Promise。我似乎无法弄清楚如何查看此承诺是否包含我正在寻找的内容。例如,Chakram.get 应该得到以下字符串:

[
 "category1",
 "category2"
]

我只是想看看它是否包含"category1"。

var chakram = require('chakram'),
    expect = chakram.expect;

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

describe("Categories", function() {
    it("should return the list of categories for devices that are installed in the project", function () {
        var response = chakram.get("https://192.168.2.2/category");
        expect(response).to.have.status(200);
        expect(response).not.to.have.header('non-existing-header');
        expect(response).to.contain('category1');
        return chakram.wait();
    });
});

如您所见,我已经尝试了上面的 to.contain 行,但出现以下异常。我认为这是因为 Chai 不喜欢对象类型。不确定我是否需要将 Promise 转换为不同的对象类型?如果是,怎么做?

TypeError: obj.indexOf is not a function
  at include (/Users/acme/node_modules/chai/lib/chai/core/assertions.js:228:45)
  at /Users/acme/node_modules/chakram/node_modules/chai-as-promised/lib/chai-as-promised.js:304:26
  at _fulfilled (/Users/acme/node_modules/chakram/node_modules/q/q.js:834:54)
  at self.promiseDispatch.done (/Users/acme/node_modules/chakram/node_modules/q/q.js:863:30)
  at Promise.promise.promiseDispatch (/Users/acme/node_modules/chakram/node_modules/q/q.js:796:13)
  at /Users/acme/node_modules/chakram/node_modules/q/q.js:604:44
  at runSingle (/Users/acme/node_modules/chakram/node_modules/q/q.js:137:13)
  at flush (/Users/acme/node_modules/chakram/node_modules/q/q.js:125:13)

我想你正在寻找 response.body

expect(response.body).to.contain('category1');

这里有一个完整的例子:

  it("should support sequential API interaction", function () {
    return chakram.get("url")
    .then(function (response) {
      expect(response.body).to.contain("thing");
    });
  });

您可以将 response.body 字符串化,然后使用函数索引来检查它是否包含您期望的内容。