Home Blog CV Projects Patterns Notes Book Colophon Search

Testing using Tape and a Logger

12 Jan, 2017

npm install --save-dev tape

Then:

const test = require('tape')

function capturingLogger (spec) {
  let messages = []
  let currentMessage = 0
  let lastInspectedMessage = 0
  function log (...args) {
    currentMessage++
    messages.push(args)
  };
  function last () {
    const slice = messages.slice(lastInspectedMessage, currentMessage)
    lastInspectedMessage = currentMessage
    return slice
  }
  return Object.freeze({
    log,
    last
  })
}

function run (log) {
  log('Running!')
  return Promise.resolve({msg: 'Success!'})
}

test('before', function (t) {
  // Do some setup, perhaps create a server etc
  t.end()
})

test('e2e test success', function (t) {
  const logger = capturingLogger()
  run(logger.log).then((result) => {
    t.ok('msg' in result, 'Received a "msg" key')
    t.equal(result.msg, 'Success!', 'Got the correct message')
    t.deepEqual(logger.last(), [
        [ 'Running!' ]
    ], 'Got the expected log messages')
    t.end()
  }).catch((err) => {
    t.fail('Did not expect error', err)
    t.end()
  })
})

test('after', function (t) {
  // Cleanup, perhaps stop the server etc.
  t.end()
})

Gives:

TAP version 13
# before
# e2e test success
ok 1 Received a "msg" key
ok 2 Got the correct message
ok 3 Got the expected log messages
# after

1..3
# tests 3
# pass  3

# ok

There are a few things I like about this:

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.