【问题标题】:Chai not reaching .end()柴没有到达 .end()
【发布时间】:2016-09-08 13:33:54
【问题描述】:

我正在使用 Mocha 和 Chai 测试我的 Node/Express API,但我无法弄清楚为什么测试没有到达 .end()

这是测试:

it('should authenticate successfully with user credentials', function (done) {
    agent
        .post('/login')
        .set('Content-Type', 'application/x-www-form-urlencoded')
        .send({ 'username': 'username', 'password': 'password'})
        .end(function (err, res) {
            console.log(res);
            console.log('***************************Authenticated*********************************************');
            expect(res).to.have.status(200);
        });
    done();
});

这是我要走的路线:

app.post('/login', passport.authenticate('ldapauth', { successRedirect: '/' }));

我认为我的问题可能在于没有正式响应,而是重定向,但我不确定如何处理它。

【问题讨论】:

  • 首先将done()移动到end处理程序内部

标签: node.js express mocha.js chai api-design


【解决方案1】:

如果您正在测试异步方法 int mocha,您应该在回调函数中调用 call 方法,如下所示。

it('should authenticate successfully with user credentials', function (done) {
        agent
            .post('/login')
            .set('Content-Type', 'application/x-www-form-urlencoded')
            .send({ 'username': 'username', 'password': 'password'})
            .end(function (err, res) {
                console.log(res);
                console.log('***************************Authenticated*********************************************');
                expect(res).to.have.status(200);
                done();
            });

    });

【讨论】:

    【解决方案2】:

    解决方案最终是将 done() 回调移动到我的 .end() 方法中。谢谢@robertklep

    【讨论】:

      【解决方案3】:

      我对 chai 请求有同样的问题。我想在转到另一个函数之前等待 .end 回调。但我不能用摩卡,因为我用的是黄瓜。如何等待 chai .end 回调? 事实上,我想先记录(1)但它不能正常工作

      When('I submit with method {string}:', function (string, docString) {
        chai.request(app)
        .post(endpoint)
        .send(docString)
        .end(function (err, res) {
          console.log(1)
          response = res
        })
      });
      
      Then('I recieved ok', function () {
        console.log(2)
        // expect(response.status).to.deep.equal(200)
      });
      

      【讨论】:

        猜你喜欢
        • 2014-05-10
        • 2013-08-19
        • 2021-07-26
        • 2014-07-02
        • 2018-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-10
        相关资源
        最近更新 更多