Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

how to test a nodejs exports that contains async function

how to test a nodejs exports that contains async function

Problem

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?

Problem courtesy of: charleetm

Solution

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
Solution courtesy of: ikaruss

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

how to test a nodejs exports that contains async function

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×