Testing Vanilla Javascript With Jest

Testing Vanilla Javascript With Jest

5 min read Jun 18, 2024
Testing Vanilla Javascript With Jest

Testing Vanilla JavaScript with Jest

Jest is a popular JavaScript testing framework developed by Facebook. It's known for its ease of use, comprehensive features, and fast execution. Jest is especially well-suited for testing Vanilla JavaScript projects, offering a streamlined and powerful testing experience.

Why Jest for Vanilla JavaScript?

  • Zero Configuration: Jest comes with minimal setup, allowing you to focus on writing tests without getting bogged down in configuration details.
  • Snapshot Testing: Jest's snapshot feature automatically generates a "snapshot" of your component's output, allowing you to easily detect unexpected changes.
  • Mocking and Spies: Jest provides powerful mocking capabilities, making it easy to isolate and test specific parts of your code.
  • Asynchronous Testing: Jest seamlessly handles asynchronous code, ensuring your tests run smoothly and reliably.
  • Extensive Documentation and Community: Jest has a comprehensive documentation and a vibrant community, making it easy to get started and find solutions to your problems.

Setting Up Jest

  1. Install Jest:

    npm install jest --save-dev
    
  2. Create a Jest Configuration File: Create a file named jest.config.js in the root of your project and add the following configuration:

    module.exports = {
      preset: 'jest-preset-jsdom', // Use jsdom to simulate a browser environment
      setupFilesAfterEnv: ['/setupTests.js'], // Optional: For global setup
    };
    
  3. Create a Test File: Create a file named myFunction.test.js in a __tests__ directory (or any directory you prefer).

Writing Your First Test

Here's a simple example of a test for a function that adds two numbers:

// myFunction.js
function sum(a, b) {
  return a + b;
}

// myFunction.test.js
const { sum } = require('./myFunction');

describe('sum function', () => {
  it('should add two numbers correctly', () => {
    expect(sum(2, 3)).toBe(5);
  });
});

Running Your Tests

Run your tests using the following command:

npm test 

Jest will automatically detect and run all your test files.

Example: Testing a DOM Manipulation Function

// myDomFunction.js
function addListItem(list, itemText) {
  const newItem = document.createElement('li');
  newItem.textContent = itemText;
  list.appendChild(newItem);
}

// myDomFunction.test.js
const { addListItem } = require('./myDomFunction');
const { JSDOM } = require('jsdom');

describe('addListItem function', () => {
  let list, dom;

  beforeEach(() => {
    dom = new JSDOM('
    '); list = dom.window.document.getElementById('myList'); }); it('should add a new list item to the list', () => { addListItem(list, 'New Item'); // Assertions using the simulated DOM expect(list.children.length).toBe(1); expect(list.children[0].textContent).toBe('New Item'); }); });

    Key Concepts

    • describe: Defines a test suite.
    • it: Defines an individual test case.
    • expect: Used for making assertions about the expected outcome of your code.
    • toBe: Matches the actual value with the expected value.
    • toMatchSnapshot: Compares the output of a component with a previously saved snapshot.
    • mock: Creates a mock object that can be used to control the behavior of external dependencies.
    • spy: Tracks the calls made to a function, allowing you to verify its behavior.

    Conclusion

    Jest provides a robust and user-friendly testing framework for Vanilla JavaScript projects. Its ease of use, comprehensive features, and powerful mocking capabilities make it an excellent choice for developers looking to write comprehensive and reliable tests for their JavaScript code.

    Related Post