Mochajs locally in your symfony project

How to install node and mocha locally to unit test you javascript code

I will install packages in the require-dev section of my composer.json file, because in this case, I only use nodejs and mocha in the dev, preprod and test environments and they use the requierdev.
I don’t want to install that on my production environment.

To do that, I use two composer packages:

mouf/nodejs-installer

Packagist: https://packagist.org/packages/mouf/nodejs-installer
Github: https://github.com/thecodingmachine/nodejs-installer

koala-framework/composer-extra-assets

Packagist: https://packagist.org/packages/koala-framework/composer-extra-assets
Github: https://github.com/koala-framework/composer-extra-assets

Here the installation

You have to add this to composer.json file:

"require": {
    "mouf/nodejs-installer": "^1.0",
    "koala-framework/composer-extra-assets": "~1.1"
},
"extra": {
    "require-dev-npm": {
        "mocha": "*"
    }
}

To use mocha locally you have to add one file to the bin directory of your symfony project

In the script section, both in « post_install_cmd » and « post_update_cmd »

"touch bin/mocha && chmod +x bin/mocha && echo '#!/bin/bash \n DIR=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd ) \n export PATH=$DIR/../vendor/nodejs/nodejs//bin:$PATH \n ../node_modules/.bin/mocha \"$@\"' > bin/mocha"

Example:

],
    "scripts": {
        "post-root-package-install": [
            "SymfonyStandard\\Composer::hookRootPackageInstall"
        ],
        "post-install-cmd": [
            [...] //do not copy/paste, it's just an example !
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles",
            "touch bin/mocha && chmod +x bin/mocha && echo '#!/bin/bash \n DIR=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd ) \n export PATH=$DIR/../vendor/nodejs/nodejs//bin:$PATH \n ../node_modules/.bin/mocha \"$@\"' > bin/mocha"
        ],
        "post-update-cmd": [
            [...]  //do not copy/paste, it's just an example !
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles",
            "touch bin/mocha && chmod +x bin/mocha && echo '#!/bin/bash \n DIR=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd ) \n export PATH=$DIR/../vendor/nodejs/nodejs//bin:$PATH \n ../node_modules/.bin/mocha \"$@\"' > bin/mocha"
        ]
    },

This line will create the mocha file and set the execution permission.

To actually install these:

composer install

Create a js directory src/Tests

With you IDE, or

mkdir src/Tests/Js

Finally use it just like that

Run all tests files:

bin/mocha src/Tests/Js/*

Or specific one:

bin/mocha src/Tests/Js/file.js

That’s it ! You can now unit test easily your javascript code !

As always, if you have question,  better practice, suggestion comment !