» Quick Introduction to JavaScript » 2. Advanced » 2.6 Testing

Testing

Testing in JavaScript projects is a crucial aspect of ensuring code reliability and maintainability. There are various testing frameworks and libraries available in the JavaScript ecosystem.

Unit Testing

Popular unit testing libraries include Jest, Mocha, and Jasmine.

Let's use Jest as an example here.

# Install Jest using npm
npm install --save-dev jest
// math.js
function add(a, b) {
  return a + b;
}

module.exports = add;

Create a test file with the same name as the module you're testing, suffixed with .test.js.

// math.test.js
const add = require('./math');

test('adds 1 + 2 to equal 3', () => {
  expect(add(1, 2)).toBe(3);
});

Run tests using:

npm test

End-to-End Testing

Popular testing frameworks include Cypress, Selenium and Puppeteer.

Let's use Cypress as an example here.

# Install Cypress using npm
npm install --save-dev cypress

Create a test file inside the cypress/integration directory.

// example_spec.js
describe('My First Test', function () {
  it('Visits the Kitchen Sink', function () {
    cy.visit('https://example.cypress.io');

    cy.contains('type').click();

    // Should be on a new URL which includes '/commands/actions'
    cy.url().should('include', '/commands/actions');

    // Get an input, type into it, and verify that the value has been updated
    cy.get('.action-email')
      .type('test@example.com')
      .should('have.value', 'test@example.com');
  });
});

Updathe the package.json to add scripts.

"scripts": {
  "cypress": "cypress open"
}

And then run the tests:

npm run cypress

These are general steps, and the specific implementation details may vary. Always refer to the documentation of the testing tools and libraries you choose for more detailed information.

Libraries & Frameworks