1

I have a unit test for my testService. I call a function create which calls another subfunction save which mirrors (apiService.send) the data to a national server. In my unit test I don't want to test the connection to a server etc. so I want to mock the function apiService.send and instead always return a certain value. But I still want to keep the rest of the save function, because I really want to check if everything was saved well in the database.

As far as I read Jasmine - How to spy on a function call within a function? this can be achieved with and.callThrough

test

testService.createTest(appUser, testData, (err, test) ->
  expect(err).toBe(null)
  ...

function

saveTest = (test, method, appUserToken, callback) ->
  async.parallel
    local: (next)->
      test.save((err) ->
        return next err if err?
        return next null, test._id
      )
    national: (next)->
      apiService.send(environment, method, test, appUserToken, (err, testId) ->
        return next err if err?
        TestModel.update({_id: test._id},  { $set: { refId: new Object(testId) }}, (err, result) ->
          return next err if err?
          return next 'Referenz Id wurde nicht gespeichert' if result.nModified==0
          return next null, test._id
        )
      )
    (err, results)->
      return callback err if err?
      return callback null, results.local


exports.createTest = (appUser, testData, callback) ->
  ...
  saveTest(newTest, 'createTest', appUser.token, callback)
Community
  • 1
  • 1
Andi Giga
  • 3,744
  • 9
  • 38
  • 68
  • Searched for the wrong term, I guess this looks like what I was looking for: http://stackoverflow.com/questions/5747035/how-to-unit-test-a-node-js-module-that-requires-other-modules I will post a solution as soon as I get it working – Andi Giga Oct 07 '15 at 09:56

1 Answers1

1

The module proxyquire (https://github.com/thlorenz/proxyquire) can be used to achieve the solution:

proxyquire =  require('proxyquire').noCallThru()
apiServiceStub = {}

Require your original module through proxyquire. For the module you want to overwrite is important to use the same path as in your original module. In this case: ../api/api.service.js

testService = proxyquire(applicationDir + 'backend/test/test.service.js', '../api/api.service.js': apiServiceStub)

Write a fake function

apiServiceStub.send = (environment, method, data, token, callback) ->
  console.log "I'm a fake function"
  return callback null, testDummies.SUPERADMIN_ID
Andi Giga
  • 3,744
  • 9
  • 38
  • 68