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

How do I test JavaScript code with Jest?

Asked on Sep 10, 2024

Answer

Jest is a popular testing framework for JavaScript, especially for applications built with React. It allows you to write tests with an easy-to-use API.
<!-- BEGIN COPY / PASTE -->
        // Example function to test
        function add(a, b) {
            return a + b;
        }

        // Jest test case
        test('adds 1 + 2 to equal 3', () => {
            expect(add(1, 2)).toBe(3);
        });
        <!-- END COPY / PASTE -->
Additional Comment:
  1. Install Jest using npm with the command: "npm install --save-dev jest".
  2. Create a JavaScript file with the function you want to test, e.g., "add.js".
  3. Create a test file, e.g., "add.test.js", and include the test code as shown above.
  4. Run your tests using the command: "npx jest".
  • Jest automatically finds files with ".test.js" or ".spec.js" extensions.
  • Use "expect" to define assertions and "toBe" to check for equality.
✅ Answered with JavaScript best practices.
← Back to All Questions