vendredi 8 avril 2016

Writing unit tests in the same file where function is declared

I'm looking for a different kind of javascript testing suite. I want to create functions and tests side-by-side in the same file. I really like not having to switch back and fourth between files when I just want to test something simple.

Below I have an example of a missingProperties and it also has an accompanying __test__missingProperties function.

example.js

import { zipObject, get, chain } 'lodash'

export function missingProperties (obj, properties) {
  properties = zipObject(properties, properties)
  let result = chain(properties)
  .mapValues(item => {
    return get(obj, item)
  })
  .filter(value => (typeof value === undefined))
  .keys()
  .values()
  if (!result.length) return false
  return result
}

export function __test__missingProperties (assert) {
  assert.deepEqual(missingProperties({'name': 'Thomas'}, ['name']), false)
  assert.deepEqual(missingProperties({'name': 'Thomas'}, ['age']), ['age'])
  assert.deepEqual(missingProperties({'name': 'Thomas'}, ['age', 'email']), ['age', 'email'])
}

This just feels much more consistent, easier to write, create tests, and edit the function.

tests.js

import * as example from './example'

export default { example }

The tests file would have access to every exported function and would need to check every property for functions prefaced with __test__, then run them all.

The only downside to this I can think of is that when I'm using something like browserify or webpack the entire file will be bundled, including these tests, increasing the bundle size with unnecessary code. Ideally I can use a tool like rollup to only pull in functions used. Are there any real downsides to this method of testing functions? Is there anything like this that already exists?

Aucun commentaire:

Enregistrer un commentaire