Saturday, May 18, 2013

test functions with mocha

If test/test.js looks like this:

function myFunction(six, seven)
{
   return 42;
}
var assert = require("assert")
   describe('Array', function(){
   describe('meaning of everything', function(){
      it('should multiply the two numbers handed in', function(){
         var result = myFunction(6,7);
         assert.equal(result, 42);
      })
   })
})

 
 

Clearly, I am able to use mocha to test myFunction as myFunction sits in the same .js file as its test. The test above passes (or fails if I change the 42 to a 43). What is more, I can then latch onto test/test.js with, for example, an HTML file sitting one folder up from the test folder. In making a connection, I may use myFunction in HTML and I am pleased to report that the extra mocha stuff in the file causes no errors or drama.

<!DOCTYPE html>
<html lang="en">
   <body>
      <div id="putsomethinghere"></div>
      <script src="test/test.js"></script>
      <script language="javascript" type="text/javascript">
         var result = myFunction(6,7);
         document.getElementById('putsomethinghere').innerHTML = result;
      </script>
   </body>
</html>

 
 

It seems to me that one way to go about mocha.js testing of functions would be to do something like this. In this model numerous files could live in the test folder and be referenced by applications. Node.js should run all the tests in the test folder spread across different files as best as I can tell. Pain points might come into play when one does a release of an application once it is baked to a point where a version goes out the door. The paths which reference the test folder would likely be rewritten to be something else and the mocha tests themselves may have to be stripped out in the name of minification accentuation. That said, this is perhaps a minor headache at best and it seems like one could get used to this being a part of the deployment dance. The other way to skin this cat would be to somehow have myFunction in a separate file that test/test.js references and while this may be a better way to go I have yet to figure out how to get it to work. I have struggled with require.js some and there may be a way to get a .js file to consume another .js file without an HTML file wiring up the dependencies with require.js, but I have not yet been able to figure out the magic myself. Outside of require.js, I have been unable to make a new document (in code in JavaScript) without having a document (again we are back to needing an HTML document to associate .js files) in the name of consuming a .js file. I have seen examples online of reading a .js file from a .js file but they all assume that you can either use document.whatever or something called DOMParser() and you cannot do these from within a standalone .js file. Does anyone know if there is a really easy trick that I'm missing?

No comments:

Post a Comment