Scott Fister
Scott Fister

Reputation: 1283

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({});
  });
});

Upvotes: 2

Views: 530

Answers (2)

Moika Turns
Moika Turns

Reputation: 801

Had similar issue and addressed it in a way that allows regular unit test frameworks like Jest and Mocha access, without modifying the original JavaScript files. Answered here.

Upvotes: 0

Florian Orpeliere
Florian Orpeliere

Reputation: 184

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.

Upvotes: 2

Related Questions