2013-12-08 24 views
2

我正在嘗試使用Mocha/Chai的chai-http插件。其中包裹Superagent。一切似乎運作良好,除了我想知道...在Node中只進行chai-http單元測試的1次http調用?

我不應該能夠使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 

但我想運行幾個斷言,並在自己的「它」塊有他們每個人。

是否有一種方式來運行

before -> 

然後只需調用響應的價值我的說法?

回答

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

我注意到你沒有在您的示例使用done回調。將它用於異步測試非常重要。在上面顯示的代碼中,before回調是異步的,但測試本身是同步的。

+0

非常感謝你的回覆@Louis,done()非常有意義。 – Adam

+0

但是,我已經像你的例子那樣設置了我的函數,並且我得到了404。當我將它移回時,我得到了預期的200.我錯過了什麼?我可以告訴你我的代碼,但它幾乎完全是你上面所說的...... – Adam

+0

這是錯誤:AssertionError:expected {Object(req,res,...)}有狀態碼200但是有404 – Adam

相關問題