JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What is Mocha and how do I use it for testing?

Asked on Sep 11, 2024

Answer

Mocha is a popular JavaScript testing framework that runs on Node.js and in the browser, designed to make asynchronous testing simple and fun. It provides a flexible structure for writing and organizing tests.
<!-- BEGIN COPY / PASTE -->
        // Import the assert module
        const assert = require('assert');

        // Describe a test suite
        describe('Array', function() {
            // Define a test case
            it('should return -1 when the value is not present', function() {
                assert.strictEqual([1, 2, 3].indexOf(4), -1);
            });
        });
        <!-- END COPY / PASTE -->
Additional Comment:
  • Mocha allows you to structure your tests using "describe" blocks for test suites and "it" blocks for individual test cases.
  • The "assert" module is used here for assertions, but you can use other assertion libraries like Chai.
  • To run tests, install Mocha globally with "npm install -g mocha" and execute "mocha" in your terminal.
  • Mocha supports both synchronous and asynchronous testing.
✅ Answered with JavaScript best practices.
← Back to All Questions