How do I test a piece of code using Mocha.js?



  • I'm dealing with js and testing, a I have a question. There is a script with different functions - script.js; Installed nodejs with chai.js and mocha.js; I wrote an example test, it stumbles, saying that "viewCookie is not defined"

    var assert = require ('assert');
    describe ('Cookies', function () {
        describe ('viewCookie ()', function () {
            it ('should return undefined', function () {
                assert.equal (undefined, viewCookie ());
            });
        });
    });
    

    How to properly run a test of only one function from script.js? and how to refer to it correctly from the directory where the test is located? and also what to do if the function requests parameters like document. etc., I would like to somehow substitute possible values ​​there.



  • Try to include your script.js file as a module. You can do this via require ('./ script.js') (the path is specified relative to the file with the test). But in this case, you must add module.exports = * value * at the end of the script.js file. Instead of a value, there will be an object containing the functions that you are going to test, for example, {viewCookie: viewCookie, anotherFunction: anotherFunction} Then in the test module, you can call them through a variable having connected a file with functions.

    var script = require ('./ script.js');
    var assert = require ('assert');
    describe ('Cookies', function () {
        describe ('viewCookie ()', function () {
            it ('should return undefined', function () {
                assert.equal (undefined, script.viewCookie ());
            });
        });
    });
    

    If you want to use this file with functions in a browser, then you should check for the presence of module.exports, since this construction is peculiar to Node.js.You can do this as follows:

    if (typeof module! == 'undefined' && typeof module.exports! == 'undefined') {
      module.exports = * value *;
    }
    


Suggested Topics

  • 3
  • 2
  • 2
  • 2
  • 4