如何在mocha中编写一个post请求测试,用数据来测试响应是否匹配?

时间:2015-07-02 05:52:51

标签: node.js mocha karma-mocha

问题: 如何在mocha中编写一个post请求测试,测试响应是否匹配?

响应只是一个url字符串,因为它是第三方服务的重定向。

工作示例有效负载:

<?php echo get_the_excerpt(); ?> instead of <?php the_excerpt(); ?>

member.controller.js //发布方法

curl -H "Content-Type: application/json" -X POST -d '{"participant":{"nuid":"98ASDF988SDF89SDF89989SDF9898"}}' http://localhost:9000/api/members

预期res.send

// Creates a new member in the DB.
exports.create = function(req, res) {
  Member.findByIdAndUpdate(req.body.participant.nuid,
    { "$setOnInsert": { "_id": req.body.participant.nuid } },
      { "upsert": true },
      function(err,doc) {
        if (err) throw err;
        res.send({
          'redirectUrl': req.protocol + '://' + req.get('host') + '/registration/' + req.body.participant.nuid
        })
    }
  );
};

工作示例GET请求测试

 {"redirectUrl":"http://localhost:9000/registration/98ASDF988SDF89SDF89989SDF9898"}  

2 个答案:

答案 0 :(得分:14)

试试这个:

  it('should respond with redirect on post', function(done) {
        request(app)
          .post('/api/members')
          .send({"participant":{"nuid":"98ASDF988SDF89SDF89989SDF9898"}})
          .expect(200)
          .expect('Content-Type', /json/)
          .end(function(err, res) {
            if (err) done(err);
            res.body.should.have.property('participant');
            res.body.participant.should.have.property('nuid', '98ASDF988SDF89SDF89989SDF9898');

             });
          done();
      });

答案 1 :(得分:1)

您也可以将类型设置为&#34; form&#34;和内容类型为json,如下所示:

it("returns a token when user and password are valid", (done) => {
    Users.createUserNotAdmin().then((user: any) => {
        supertestAPI
        .post("/login")
        .set("Connection", "keep alive")
        .set("Content-Type", "application/json")
        .type("form")
        .send({"email": user.email, password: "123456"})
        .end((error: any, resp: any) => {
            chai.expect(JSON.parse(resp.text)["token"].length).above(400, "The token length should be bigger than 400 characters.");
            done();
        })
    });
});

您还必须在创建服务器时设置正文解析器,如下所示:

 server.use(bodyParser.urlencoded({ extended: false }));
 server.use(bodyParser.json());
相关问题