尝试在Mocha测试中调用服务器URL时出现TypeError

时间:2019-04-01 06:38:23

标签: node.js mocha chai

我正在尝试对进行用户注册的API进行单元测试。但是得到一个,

 TypeError: "string" must be a string, Buffer, or ArrayBuffer

这是我的代码块,

describe("User registration unit test", ()=>{
  it("The users should be able to register with proper credentials", ()=>{
    return chai.request(testServer)
              .post("/api/auth/register")
              .set("Content-Type", "application/x-www-form-url-encoded")
              .send({
                "name": "Jithin333",
                "email": "jtihin324@gmail.com",
                "password": "Jithin12!",
                "role": "user"
              }).then((res)=> {
                expect(res).to.have.status(201);
                done();
              })
  });
});

2 个答案:

答案 0 :(得分:0)

我认为您应该传递一个字符串而不发送对象。在将对象传递给发送之前,尝试JSON.stringifying对象。如下所示。

describe("User registration unit test", ()=>{
  it("The users should be able to register with proper credentials", ()=>{
    return chai.request(testServer)
              .post("/api/auth/register")
              .set("Content-Type", "application/json")
              .send({
                "name": "Jithin333",
                "email": "jtihin324@gmail.com",
                "password": "Jithin12!",
                "role": "user"
              }).then((res)=> {
                expect(res).to.have.status(201);
              });
  });
});

答案 1 :(得分:0)

您好,找到答案添加JSON.stringify并删除done()应该可以工作

 it("The users should be able to register with proper credentials", ()=>{
    return chai.request(testServer)
              .post("/api/auth/register")
              .set("Content-Type", "application/json")
              .send(JSON.stringify({
                "name": "Jithin",
                "email": "jtihindr1@gmail.com",
                "password": "Jithin12!",
                "role": "user"
              })).then((res)=> {
                expect(res).to.have.status(201);
      });