Replacing internal functions with testdouble.js?

1.2k Views Asked by At

Is it possible to td.replace an internal function in a node.js module when testing with testdouble.js?

The internal function consists of a DB call, so I do not want to test it. I do however want to test that this function received the expected parameters.

For example, given a node.js module:

module.exports = { record: recordEvent }

recordEvent = (event) =>
    var dbModel = map(event);
    persist(dbModel);

var map = (event) => 
    // some code that transforms event to the db specific representation (testable)

var persist = (model) =>
    // some SQL insert/update code here (not testable)

And the following test, that checks if persist gets the correct params:

recorder = require('event_recorder')
describe 'Event recorder module', ->
    it 'converts the event to a db model', ->

        var event = {...// mock event };
        var model = {...// mock model of the event };

        var persist = td.replace(recorder, 'persist')
        td.when(persist(model)).thenReturn(true)

        result = recorder.record(event)
        expected = true;

        result.should.be.equal(expected)

However the test throws an error:

td.replace - No "persist" property was found

I understand why it has this error, its because the persist method is not public. How else can I achieve this in testdouble?

1

There are 1 best solutions below

0
On

One option, as you insinuated, is to make the persist method public. Another option would be for persist to accept or make use of another function to perform the SQL query, and stub that function instead:

var executeQuery = td.function()

recorder.recordEvent(event, executeQuery)

td.verify(executeQuery('UPDATE ...'))