logo
eng-flag

Jest Cheatsheet

Table of Contents

  1. Introduction
  2. Installation
  3. Basic Test Structure
  4. Matchers
  5. Asynchronous Tests
  6. Mocking
  7. Setup and Teardown
  8. Grouping Tests
  9. Snapshot Testing
  10. Coverage Reports
  11. Best Practices

Introduction

Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!

Installation

To install Jest, run the following command:

npm install --save-dev jest

Add the following section to your package.json:

{
  "scripts": {
    "test": "jest"
  }
}

Basic Test Structure

A basic test in Jest looks like this:

test('description of the test', () => {
  // Your test code here
  expect(someValue).toBe(expectedValue);
});

You can also use it instead of test:

it('should do something', () => {
  // Your test code here
});

Matchers

Jest uses "matchers" to let you test values in different ways. Here are some common matchers:

Exact Equality

expect(2 + 2).toBe(4);

Object Matching

expect({name: 'John', age: 30}).toEqual({name: 'John', age: 30});

Truthiness

expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect(true).toBeTruthy();
expect(false).toBeFalsy();

Numbers

expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);

Strings

expect('team').not.toMatch(/I/);
expect('Christoph').toMatch(/stop/);

Arrays and iterables

expect(['Apple', 'Banana', 'Orange']).toContain('Banana');

Exceptions

expect(() => {
  throw new Error('You are using the wrong JDK');
}).toThrow();

expect(() => {
  throw new Error('You are using the wrong JDK');
}).toThrow('You are using the wrong JDK');

expect(() => {
  throw new Error('You are using the wrong JDK');
}).toThrow(/JDK/);

Asynchronous Tests

Promises

test('the data is peanut butter', () => {
  return fetchData().then(data => {
    expect(data).toBe('peanut butter');
  });
});

Async/Await

test('the data is peanut butter', async () => {
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});

Callbacks

test('the data is peanut butter', done => {
  function callback(data) {
    try {
      expect(data).toBe('peanut butter');
      done();
    } catch (error) {
      done(error);
    }
  }

  fetchData(callback);
});

Mocking

Mock Functions

test('mock implementation of a function', () => {
  const mock = jest.fn(() => 'bar');

  expect(mock('foo')).toBe('bar');
  expect(mock).toHaveBeenCalledWith('foo');
});

Mock Modules

jest.mock('./myModule');

const myModule = require('./myModule');

test('should do something', () => {
  myModule.someFunction.mockReturnValue('mocked value');
  expect(myModule.someFunction()).toBe('mocked value');
});

Mock Timers

jest.useFakeTimers();

test('waits 1 second before ending the game', () => {
  const timerGame = require('../timerGame');
  timerGame();

  expect(setTimeout).toHaveBeenCalledTimes(1);
  expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
});

Setup and Teardown

beforeAll(() => {
  // Runs before all tests
});

afterAll(() => {
  // Runs after all tests
});

beforeEach(() => {
  // Runs before each test
});

afterEach(() => {
  // Runs after each test
});

Grouping Tests

describe('matching cities to foods', () => {
  test('Vienna <3 sausage', () => {
    expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
  });

  test('San Juan <3 plantains', () => {
    expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
  });
});

Snapshot Testing

it('renders correctly', () => {
  const tree = renderer
    .create(<Link page="http://www.facebook.com">Facebook</Link>)
    .toJSON();
  expect(tree).toMatchSnapshot();
});

Coverage Reports

Add the following section to your package.json:

{
  "jest": {
    "collectCoverage": true,
    "coverageReporters": ["json", "lcov", "text", "clover"]
  }
}

Or use the --coverage flag when running Jest.

Best Practices

  1. Test Description: Write clear and descriptive test names.

  2. Arrange-Act-Assert: Structure your tests using the AAA pattern.

  3. Don't test implementation details: Focus on testing the public API of your modules.

  4. Avoid duplication: Use beforeEach and afterEach to avoid repeating setup and teardown code.

  5. Mock external dependencies: Use mocking to isolate the code you're testing.

  6. Keep tests simple: Each test should verify one specific behavior.

  7. Run tests in isolation: Tests should not depend on each other.

  8. Use test.only for debugging: When debugging, use test.only to run only one test.

  9. Update snapshots carefully: Always review snapshot changes before updating them.

  10. Continuous Integration: Run your tests as part of your CI/CD pipeline.

2024 © All rights reserved - buraxta.com