Search code examples
javascriptunit-testingamdnode.js-tape

Testing AMD modules with tape/ES6 unit tests?


I have a web app using:

  • ES5
  • RequireJS
  • Underscore
  • Backbone
  • jQuery

I have tried setting up a new unit test suite using:

  • ES6
  • Tape
  • Babel6

My AMD module app/util/stringUtil.js:

define([], function() {
    'use strict';

    return {
        isBlank: function(str) {
            return _.isUndefined(str) || _.isNull(str) || _.isString(str) && str.trim().length === 0;
        }
    };
});

My unit test in tapeTest.js:

import test from 'tape';
import sortUtil from 'app/util/stringUtil';

test('Testing stringUtil', (assert) => {

    assert.ok(stringUtil.isBlank('   ')),
        'Should be blank');

    assert.end();
});

My .babelrc:

{
  "presets": ["es2015"]
}

I run the test with tape:

tape -r babel-register tapeTest.js

I get the following error:

app/util/stringUtil.js:1
(function (exports, require, module, __filename, __dirname) { define([], function () {
                                                              ^
ReferenceError: define is not defined
    at Object.<anonymous> (stringUtil.js:1:23)
    at Module._compile (module.js:434:26)
    at loader (node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (tapeTest.js:7:17)
    at Module._compile (module.js:434:26)

I'm guessing tape doesn't recognize AMD modules? Can I fix this somehow? Maybe transpile AMD modules to CommonJS modules or something?


Solution

  • You can load AMD modules inside node with requirejs :_)

    Read here: http://requirejs.org/docs/node.html

    You have to import require and do a little config, something like this:

    'use strict';
    
    const test = require('tape');
    const requirejs = require('requirejs');
    
    requirejs.config({
        baseUrl: __dirname,
        nodeRequire: require
    });
    
    test('Test something', function (assert) {
        requirejs(['app/util/stringUtil'], function   (stringUtil) {
    
            assert.ok(stringUtil.isBlank('   '), 'Should be blank');
    
            assert.end();
        });
    });