【问题标题】:Make only 1 http call for chai-http unit-testing in Node?在 Node 中只对 chai-http 单元测试进行 1 个 http 调用?
【发布时间】:2013-12-25 20:48:07
【问题描述】:

我正在试用 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

但我想运行几个断言,并将它们中的每一个都放在自己的“it”块下。

有没有办法运行

   before ->

然后就调用我对响应值的断言?

【问题讨论】:

    标签: node.js unit-testing testing mocha.js chai


    【解决方案1】:

    是的,像这样:

    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 回调是异步的,但测试本身是同步的。

    【讨论】:

    • 非常感谢@Louis 的回复,done() 非常有意义。
    • 但是,我已经像您的示例一样设置了我的函数,我得到了 404。当我将它移回时,我得到了预期的 200。我错过了什么吗?我可以向您展示我的代码,但它几乎就是您上面的代码......
    • 这是错误:AssertionError: expected { Object (req, res, ...) } to have status code 200 but got 404
    • 我很困惑。只是像我建议的那样移动代码不应该改变响应的状态。是否可以看到新代码? (github 上的 gist 非常适合这个,但我会通过你想使用的任何方式来查看它。)
    • 再次感谢路易斯,我真的很感激。我在这里做了一个要点:gist.github.com/seethroughtrees/7864387
    猜你喜欢
    • 2015-05-16
    • 2014-08-15
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多