npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nej-mocha

v4.3.1

Published

A test framework specifically for NEJ module system users.

Downloads

29

Readme

Mocha for NEJ Users

For NEJ users, unit testing could be a pain in the neck. This package solves the headache by letting you write mocha-chai-like test files directly with NEJ module system.

Why This?

  1. Easy to use and no boilerplates are needed. Just wrap your mocha and chai code in NEJ.define and it is done!
  2. Headless browser tests running on the latest Chromium instead of PhantomJS. Almost all new ES6 features are supported. Writing tests is just so much more efficient.
  3. Built-in coverage reports using istanbul.
  4. Dependency injections, just like inject-loader for Webpack, let you have more control over your tests.

Usage

  1. Install:

    $ npm install nej-mocha --save-dev
  2. Configure your test files in nej-mocha.conf.js. If not, all .js files under /test in your working directory will be run recursively.

  3. Run the tests:

    $ nej-mocha

    or add it in your package.json

    "scripts": {
        "test": "nej-mocha"
    }

Examples

A test file will look like this:

define([
    "{pro}/..."
], function(myModule) {
    describe("My test", function() {
        before("Some preparations", function() {
            // Anything you want to run before the tests
        });

        it("should be ok", function() {
            expect(true).to.be.true;
        });

        it("should be ok after a second", function(done) {
            setTimeout(function () {
                expect(true).to.be.true;

                done();
            }, 1000);
        });

        after("Some clean-up", function() {
            // Anything you want to run after the tests
        });
    });
});

Configurations

A configuration file can be used to configure the test runner. Create a nej-mocha.conf.js or nej-mocha.config.js under your working directory.

nej-mocha.conf.js:

module.exports = {
    //-----------------------------------------------------------------
    //-----------------------------------------------------------------
    // Optional options
    //-----------------------------------------------------------------
    //-----------------------------------------------------------------
    /**
     * Properties and nested properties to add to the `window` object. 
     * The object will be parse and add the exact same structure to the `window` object.
     *
     * Default to empty
     */
    globals: {
        // Your global properties here
    },
    /**
     * The test folder path(s) relative to your working directory.
     *
     * Only RELATIVE path is allowed.
     * Wildcard path is also supported. (E.g. './src/\*\*\/test/')
     * Can accept a string or an array
     * 
     * Default to './test'.
     */
    entries: [
        './test'
    ],
    mochaOptions: {
        /**
        * The time to wait before mocha tests exit.
        *
        * Default to 3000 ms.
        */
        timeout: 3000,
        /**
        * The mocha reporter.
        * Currently only perfectly support 'spec', 'doc', 'json', 'xunit', and 'tap'
        *
        * Default to 'spec'.
        */
        reporter: 'spec',
        /**
        * Whether the report should have colors
        *
        * Default to true.
        */
        useColors: true
        // 
        // And other supported mocha options
        // ...
    },
    /**
     * Path aliases used to passed to 'define.js' as URL parameters
     *
     * Default to only have 'pro' refering to 'src/javascript/'
     */
     nejPathAliases: {
         pro: 'src/javascript/',
         // ...
     },
     /**
      * Proxy options
      *
      * Default to empty
      */
     proxy: {
        /**
        * If you have a proxy server set up, you can pass a custom host name.
        * This will replace 'localhost'.
        * If not provided. 'localhost' is used.
        */
        host: "",
        /**
        * The port of the proxy address. Default to 'testRunnerPort'
        */
        port: 8004,
     },
     /**
      * @DEPRECATED
      * The port for the test runner server to listen on.
      *
      * Default to 8004
      */
     testRunnerPort: 8004,
     /**
      * Should the browser be closed after the tests are done
      * 
      * Default to true
      */
     shouldBrowserClosed: true,
     /**
      * Should the browser be headless when the tests are running
      * 
      * Default to true
      */
     headless: true,
     /**
      * Scripts to inject before the test html is loaded
      * Can take urls or paths relative to your working directory
      *
      * Default to empty
      */
     scriptsToInject: [
         'http://some.url/script.js',
         './some/replative/path/script.js'
     ],
     /**
      * Whether a test coverage report should be generated
      *
      * Default to false
      */
     coverage: false,
     /**
      * The test coverage tool configurations
      *
      */
     coverageOptions: {
         /**
          * Reporters used to present the coverage report
          *
          * Default to 'text'
          */
         reporters: [
             'text'
         ],
         /**
          * The files to collect coverage from
          *
          * Default to /\.js$/
          */
         include: /\.js$/,
         /**
          * The files to exclude from collecting coverage
          *
          * Default to /\.spec\.js$/
          */
         exclude: /\.spec\.js$/,
     },
     /**
      * Dependency injections
      * 
      * It replaces the patterns provided in the keys with the paths in the values. The new paths are still parsed by NEJ and therefore you can use 
      * any path patterns that NEJ can recognize.
      *
      * Do not forget to add the instruction comment in files you want to inject dependencies
      *
      * @param {RegExp|string} pattern The pattern to match
      * @param {string} path The new path to inject. If a relative path is used, it is relative to the file that has the dependency pattern.
      */
     inject: [
         {
             pattern: 'some/literal/path',
             path: 'some/new/path'
         },
         {
             pattern: /some\/regex\/path/,
             path: 'some/new/path'
         }
     ]
}

CLI Options

You can pass options in cli to override the options defined in your nej-mocha.conf.js file.

For example:

$ nej-mocha --shouldBrowserClosed=false --headless=false

This command will override shouldBrowserClosed and headless options. For more options, see configurations.

Other options:

--configPath=./path/to/your/config # Directly choose another config file. If this option is passed, other options are ignored

Dependency Injection

You can replace paths that match the given pattern with the new paths you provided at runtime. In other words, you can replace some dependencies with some mocked objects or data. Therefore you don't need and switches or back doors in your code to make it easier to test.

Usage:

  1. Add /* nej-mocha-inject */ or // nej-mocha-inject in the callback function of NEJ.define and this file will be included in dependency injections.
  2. In nej-mocha.conf.js, add options about the patterns to replace and the new paths.

Examples:

A file:

define([
    'pro/some/path/to/replace'
], function (someComplexObject) {

});

after dependency injection, will be:

define([
    'pro/some/new/path'
], function (someComplexObject) {

});

Coverage

You can generate test coverage reports by setting the coverage option in nej-mocha.conf.js to true. You can also configure the reports to use different kinds of reporters. For a whole list of reporters supported, please read the documentation of istanbul;

Optional Inline Flags:

Add /* nej-mocha-cover */ or // nej-mocha-cover in the callback function of NEJ.define and this file will be covered and added to the reports generated. Add /* nej-mocha-cover-ignore */ or // nej-mocha-cover-ignore in the callback function of NEJ.define and this file will be ignored in collecting coverage.

Precedence of Options and Flags:

Options include and exclude in coverageOptions will always be overwritten by inline flags, which means, if a file is exluced by the regular expression defined in exclude and has the flag /* nej-mocha-cover */, the file will NOT be ignored.

If/* nej-mocha-cover */ and /* nej-mocha-cover-ignore */ are both present in the function, the ignore flag will have higher priority.

API

You can also run nej-mocha programmatically

const nejMocha = require('nej-mocha');

nejMocha.run({
    config: './path/to/your/config/file'
}, (err) => {
    console.log(err);
});

or use an object directly to config nej-mocha. Options in the config object here will override options defined in nej-mocha.conf.js in your current working directory. If no config file is found, nej-mocha will use only the options defined in your config object.

const nejMocha = require('nej-mocha');

nejMocha.run({
    config: {
        entries: [
            './test'
        ],
        shouldBrowserClosed: true
        // ...
    }
}, (err) => {
    console.log(err);
});

For more API documentations, see API.

UI Testing and Debugging in Browsers

After setting the flag shouldBrowserClosed to false and starting the tests, you can open the url:

http://localhost:{testRunnerPort}/nej-mocha

in browsers to test and debug your code and UIs. The testRunnerPort can also be set in the configurations. See configurations.