在Node中只进行1次http调用以进行chai-http单元测试?

Ada*_*dam 3 testing unit-testing mocha.js node.js chai

我正在尝试用于Mocha/Chai 的chai-http插件.哪个包裹着Superagent.一切似乎都运作良好,除了我想知道......

我不应该能够进行一次http调用并为每个调用单独的测试吗?测试似乎希望您在响应函数中编写断言,如下所示:

describe "github test", ->

   it "should connect with a 200 status", ->
     chai.request(githubReqObj.base)
      .get(githubReqObj.url)
      .req (req) ->
         req.set
           'Accept': 'application/vnd.github.beta+json'
         return
      .res (res) ->
         expect(res).to.have.status 200
Run Code Online (Sandbox Code Playgroud)

但是我想运行几个断言,并将它们各自置于自己的"it"块之下.

有没有办法运行

   before ->
Run Code Online (Sandbox Code Playgroud)

然后只是在响应的价值上调用我的断言?

Lou*_*uis 5

是的,像这样:

describe("github test", function () {
    var res;

    before(function (done) {
        chai.request(...)
            .get(..)
            .req(...)
            .res(function (response) {
                res = response; // Record the response for the tests.
                done(); // Tell mocha that the ``before`` callback is done.
            });
    });

    it("should connect with a 200 status", function () {
        expect(res).to.have.status(200);
    });

    it("should whaterver", function () {
        expect(res).whatever;
    });
});
Run Code Online (Sandbox Code Playgroud)

我注意到你没有done在你的例子中使用回调.将它用于异步测试非常重要.在上面显示的代码中,before回调是异步的,但测试本身是同步的.