charleetm
charleetm

Reputation: 906

how to test a nodejs exports that contains async function

I am not sure how to test a nodejs's exports function. Consider the code below:

exports.create_expense = (req, res, next) ->
  User = database.db_model 'user'
  req.body.parsed_dt = Date.parse(req.body.date)
  req.body.amount = parseInt(req.body.amount)
  User.update {_id: req.api_session.id}, {$push: {expenses: req.body}}, (err, numberAffected, raw) ->
    if err?
      res.send 500
    else 
      res.send 200

User is a mongoose object here. I want to write a test (using mocha) to test this function (where in my test I will call create_expense) but since User.update is async I can't just call create_expense without passing some form of Promise? I know I can use supertest but that also test the route which I dont want to do here. Is there any way to test this any npm here is useful?

Upvotes: 1

Views: 88

Answers (1)

ikaruss
ikaruss

Reputation: 491

On User.update you should call next. And later in test you should call done.

edit:

Sorry for my CoffeeScript in advance.

Call next at the end of the callback to User.update.

Your test should look something like this then:

describe '#create_response', () ->
  response = false

  req.body.date = new Date
  req.body.amount = 123
  req.api_session.id = 'asd'

  res.send = (code) ->
    response = code

  it 'should return 500 on invalid request', (done) ->
    create_expense req, res, () ->
      assert.equal response, 500
      done

Upvotes: 1

Related Questions