Looking for clarifications about testing

Hello!

So I’ve been banging my head against a wall these past days on how to write tests for a small project that I did. Let’s emulate what happened:

<!-- index.html -->
<html>
    <head> ...... </head>
    <body>
        <script src="main.js"></script>
    </body>
</html>


// main.js
modules.export = { // I added this line to make testing possible
    Foo : 
    class Foo {
        bar(){
            return 42;
        }
    }
}


// test.js

const chai = require('chai');
const assert = chai.assert;

const Foo = require("./main.js").Foo;

describe("Foo", function() {
    const foo = new Foo();
    describe("bar", function() {
        it("returns 42", function() {
            assert.equal(foo.bar(), 42);
        })
    })
})

Running mocha gives a passing test, but loading index.html gives a module is not defined error. How do I work around this? Maybe you have some tips for a newbie test writer? Thanks!

One possible way:

// main.js
  class Foo {
    bar(){
        return 42;
    }
  }

if (typeof process !== 'undefined' && process.env.NODE_ENV === 'test') {
  module.exports = {Foo};
}

Edit test script in package.json:

"scripts": {
    "test": "NODE_ENV=test mocha"
  },

Run tests:

npm test
1 Like

Transpile your code to make it consumable by the browsers.
Ever heard of babel, browserify or webpack?

Alternatively, you can run tests in the browser.
Here’s how:

1 Like

browserify worked like a charm! Thanks :smiley:

May I ask your opinion on my other post? :smiley: