MAL's Logo

Jest - Basic Concepts

💡 Tips and tricks to get started testing with Jest.

Basic Test

// .test.js
describe('title situation here', () => {
	// here we can put several tests, groupped in a way that makes sense
	test("the situation that is being tested", () => {
		expect(["monkey", "seal", "elephant", "dog"].length).toBe(4);
	});

	test("another situation that is being tested", () => {
		expect(["monkey", "seal", "elephant", "dog"].length - 1).toBe('dog');
	});
});

Setup and Teardown

It is important to know that the functions below can be used outside or inside a describe() block. If used inside, the function will only affect the existing tests within.

// setup and teardown
beforeEach(() => {
	// code here runs before each existing test
});

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

afterEach(() => {
	// the code runs after each test in this file
});

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

Extra

  • not keyword - for example, can be used to turn any matcher into its opposite value, e. g. expect(0).not.toBeFalsy()
  • .toBe tests for exact equality, but to check the value of an object, .toEqual should be used
  • .toThrow helps to test functions for error handling
  • Resources

  • https://jestjs.io/docs/getting-started
  • https://jestjs.io/docs/setup-teardown
  • https://jestjs.io/docs/using-matchers
  • MAL's Logo© 2021 – 2026 MAL. All rights reserved.