Mocha与Chai HTTP异步测试?

时间:2017-09-25 19:13:03

标签: node.js async-await mocha chai

我正在使用Mocha和Chai HTTP测试Rest API。我一直在使用回调编写所有测试用例,现在我想使用async / await,因为它是一个更易读的tan回调和承诺,所以我得到这个代码:

let sport1, sport2;
let user1, user2;
let user1Token;
let event1, event2, event3, event4;

beforeEach(async function () {
  const preUser1 = test.createUser('user1@test.com');
  const preUser2 = test.createUser('user2@test.com')

  sport1 = await Sport.create(test.createSport('Tenis'));
  sport2 = await Sport.create(test.createSport('Baloncesto'));
  user1 = await User.create(preUser1);
  user2 = await User.create(preUser2);
  event1 = await Event.create(test.createEventDb(user1._id, sport1._id));
  event2 = await Event.create(test.createEventDb(user1._id, sport2._id));
  event3 = await Event.create(test.createEventDb(user2._id, sport1._id));
  event4 = await Event.create(test.createEventDb(user2._id, sport2._id));

  await chai.request(app)
    .post(`${apiPath}/sessions`)
    .set('content-type', 'application/json')
    .send({ email: preUser1.email, password: preUser1.password })
    .end(function (err, res) {
      console.log(res.body)
      user1Token = res.body.data.session.token;
    });
});

await语句工作正常,但问题在于chai。我收到此错误:

1) Events "before each" hook for "should return 200, id and event info":
 TypeError: First argument must be a string or Buffer
    at ClientRequest.end (_http_outgoing.js:605:11)
    at Test.Request.end (node_modules/superagent/lib/node/index.js:873:9)
    at node_modules/superagent/lib/request-base.js:72:12
    at Test.then (node_modules/superagent/lib/request-base.js:71:31)
    at process._tickCallback (internal/process/next_tick.js:109:7)

但是如果没有async / await调用,这个错误就不会引发。关于什么事情的任何想法?感谢。

1 个答案:

答案 0 :(得分:2)

正如@Rhayene所提到的,要将Chai与承诺一起使用,您无法使用.end()方法,这就是我收到错误的原因。因此,您只需将响应存储在变量中,然后进行所需的断言。所以,我的重构代码就是:

let sport1, sport2;
let user1, user2;
let user1Token;
let event1, event2, event3, event4;

beforeEach(async function () {
  const preUser1 = test.createUser('user1@test.com');
  const preUser2 = test.createUser('user2@test.com')

  sport1 = await Sport.create(test.createSport('Tenis'));
  sport2 = await Sport.create(test.createSport('Baloncesto'));
  user1 = await User.create(preUser1);
  user2 = await User.create(preUser2);
  event1 = await Event.create(test.createEventDb(user1._id, sport1._id));
  event2 = await Event.create(test.createEventDb(user1._id, sport2._id));
  event3 = await Event.create(test.createEventDb(user2._id, sport1._id));
  event4 = await Event.create(test.createEventDb(user2._id, sport2._id));

  const res = await chai.request(app)
    .post(`${apiPath}/sessions`)
    .set('content-type', 'application/json')
    .send({ email: preUser1.email, password: preUser1.password })

  user1Token = res.body.data.session.token;
});