简体   繁体   English

当一内一请求时,Chai-http 不检查第二个断言

[英]Chai-http is not checking second assertion when one inside one request

I am trying to get my token variable from /signing to provide it to the name change route.我正在尝试从 /signing 获取我的令牌变量,以将其提供给名称更改路线。 But the assertion is not always triggering.但断言并不总是触发。 Can there be any better way to do this?有没有更好的方法来做到这一点? Can I use async-await to solve this problem, if so, how?我可以使用 async-await 来解决这个问题吗,如果可以,如何解决?

describe("setName", function (done) {
    it("/POST user setName", function (done) {
        Users.remove({}, (err) => {
            console.log(chalk.bgBlue(`Removing User`));
            // done();
        });
        let user = {
            "email": "tiwari.ai.harsh@gmail.com",
            "password": "password",
            "name": "Harsh Tiwari"
        }
        var requester = chai.request(app).keepOpen()

        requester.post("/api/users/signin").send({
            user
        }).end((err_signin, res_signin) => {

            let token = res_signin.body.user.token;
            let name = "Name Changed"

            requester.post("/api/users/setName").set({ authorization: `Token ${token}` }).send({
                name
            }).end((err, res) => {
                res.should.have.status(200); <--------------------------- This is not working
            });

            done()
        });
    });
});

The current code will execute done before the requester.post("/api/users/setName") finish because it is an async execution.当前代码将在requester.post("/api/users/setName")完成之前执行done ,因为它是异步执行。

To solve the issue, the done() should be specified after res.should.have.status(200);为了解决这个问题, done()应该在res.should.have.status(200);

describe('setName', function (done) {

  // NOTE: I also moved remove function here to ensure user is removed correctly
  before(function(done) {
    Users.remove({}, (err) => {
      console.log(chalk.bgBlue(`Removing User`));
      done(); // NOTE: also specify done to tell mocha that async execution is finished
    });
  })

  it('/POST user setName', function (done) {
    let user = {
      email: 'tiwari.ai.harsh@gmail.com',
      password: 'password',
      name: 'Harsh Tiwari',
    };
    var requester = chai.request(app).keepOpen();

    requester
      .post('/api/users/signin')
      .send({
        user,
      })
      .end((err_signin, res_signin) => {
        let token = res_signin.body.user.token;
        let name = 'Name Changed';

        requester
          .post('/api/users/setName')
          .set({ authorization: `Token ${token}` })
          .send({
            name,
          })
          .end((err, res) => {
            res.should.have.status(200);
            done(); // NOTE: move here
          });        
      });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM