Reputation: 4162
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
testService.createTest(appUser, testData, (err, test) ->
expect(err).toBe(null)
...
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)
Upvotes: 1
Views: 715
Reputation: 4162
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
Upvotes: 1