0

Is it possible to use Jest to test individual JavaScript files without using require/export?

Let's say I want to test abc.js. Here is an example of abc.js:

(function(){
   return {
       foo: function(){}
   }
})();

Now let's say my test file is abc.test.js. I want to test if foo is a function. How would I go on about testing this file without using modules.exports in abc.js and require in abc.test.js?

Thanks in advance

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
Leo Teng
  • 93
  • 5
  • This doesn't look possible without transforming the underlying source file before Jest loads it. Is there a reason why you aren't using exports? – Lewis Chung Apr 30 '17 at 05:01
  • I don't want to include test code for my source files. I think I will have to use grunt or something to remove it for production – Leo Teng May 01 '17 at 06:47

1 Answers1

0

Use a named function, a try/catch block, and an inline assertion to test it with plain Node.js:

const assert = require('assert');

(function hi(){
  hi.foo = Function;
  try
    {
    assert.ok(typeof hi.foo === 'function', 'Not a function');
    assert.ok(typeof hi.foo === 'string', 'Not a string');
    }
  catch(e)
    {
    console.log(e.message);
    }
  }
)();

then run it:

node foo.js

Comment out the test-oriented code to avoid including it in the source file:

/*const assert = require('assert');*/

(function hi(){
  hi.foo = Function;
  /*
  try
    {
    assert.ok(typeof hi.foo === 'function', 'Not a function');
    assert.ok(typeof hi.foo === 'string', 'Not a string');
    }
  catch(e)
    {
    console.log(e.message);
    }
  */
  }
)();

Then remove the comments programmatically and pipe the output to node in a *nix shell:

cat foo.js | tr -d '/*' | node

or Powershell:

$string = cat foo.js
$string.Split("/*") | node

And use Grunt or another tool to strip out comment blocks in the build process.

References

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265