Sunday, 7 May 2017

Testdouble Injection in Node JS (Module Replacement)

I am currently using jest and testdouble.js in order to test a node app that interacts with a database. My intention is to mock out the database wrapper (a custom node module that exists in the project) and merely verify interactions. The test file looks like:

var td = require('testdouble')
var subject, profile

beforeEach(() => {
 profile = td.replace('./profile')
 console.log(profile)
 subject = require('./app');
});

test('loading app forms a database connection', () => {
  td.verify(profile.connect()) 
})

And the production code is:

var profile = require('./profile')

var connection = profile.connect()
console.log(profile)
console.log(connection)

This is logging out

console.log app.test.js:6
  { connect: { [Function: testDouble] toString: [Function] },
    insert: { [Function: testDouble] toString: [Function] },
    find: { [Function: testDouble] toString: [Function] },
    drop: { [Function: testDouble] toString: [Function] },
    toString: [Function] }
console.log app.js:4
  { connect: [Function: connect],
    insert: [Function: insert],
    find: [Function: find],
    drop: [Function: drop] }
console.log app.js:5
  Promise {
    _bitField: 0,
    _fulfillmentHandler0: undefined,
    _rejectionHandler0: undefined,
    _progressHandler0: undefined,
    _promise0: undefined,
    _receiver0: undefined,
    _settledValue: undefined }

Which seems to indicate that there is a test double in the test file that is not making it into the production code. It is also throwing:

 Unsatisfied verification on test double `.connect`.

  Wanted:
    - called with `()`.

  But there were no invocations of the test double.

  at Object.fail (node_modules/testdouble/lib/log.js:27:11)
  at exports.default [as verify] (node_modules/testdouble/lib/verify.js:46:19)
  at Object.<anonymous> (app.test.js:11:6)

Which is to be expected if the test double is not being injected (it also seems to be forming a database connection, as the console hangs after).

This seems like a very simple use case, so I apologize if there is something obvious that I am missing here.



via Michael Rauh

No comments:

Post a Comment