javascriptunit-testingtestingmocha.jschai

How do I test JS prototypes (non-modules) in Mocha/Chai?


I want to set up tests for the project I'm building. In the examples I can find, they all say including the relevant code to test is done by a require statement: require('foo');. However my project isn't built in modules, but in ES6 classes that are then translated to ES5 prototypes.

I'm wondering how to include the file/s?

So for instance the ES6 class:

class Foo {
  constructor() {
    // do things
  }
}

Translates roughly to:

// ES5 compatible code is here (_classCallCheck etc).
var Foo = (function () {    
  function Foo() {
    _classCallCheck(this, Foo);

   // do things
  }
}

And I'd like to know how to include it in my test file:

var expect   = require('chai').expect;
// how to require or whatever else here?

describe('Foo', function() {
  it('creates an Foo object', function() {
    var foo = new Foo({});
  });
});

Solution

  • If you don't use module, you can just create a simple html page for your test like this :

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>your tests</title>
      <link rel="stylesheet" media="all" href="vendor/mocha.css">
    </head>
    <body>
      <div id="mocha"><p><a href=".">Index</a></p></div>
      <div id="messages"></div>
      <div id="fixtures"></div>
      <script src="vendor/mocha.js"></script>
      <script src="vendor/chai.js"></script>
      <script src="your_files.js"></script>
      <script src="your_files_test.js"></script>
      <script>mocha.run();</script>
    </body>
    </html>
    

    With this, you don't need to require something in your test file.

    If you want more information : article

    I hope it'll help you.