Test Basics

Now that you have an understanding of the different types of testing, and have written our first test, lets look into some basic syntax and workings of a test.

Setting Up Your Test Environment

Before we proceed, ensure you have set up your project as described in the “Getting Started” section. You should have the math.mjs file containing the add function and the math.test.mjs file for writing tests.

Test Syntax

In Vitest, tests are written using the describe, it, and expect functions. Here’s a breakdown of each function:

describe Function/“block”

This function is used to group related tests together. It takes a description of the test suite and a function containing the test cases.

javascript
	describe('Describe your test suite', () => {
	  // Test cases go here
	});

For example:

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

In the image below, you will see that our test is now grouped under “Math operations”:

Describe block added

it and test Function/“block”:

This function defines an individual test case. It takes a description of the test and a function containing the test logic.

javascript
	it('Describe your test case', () => {
	  // Test logic goes here
	});

Note: The it and test functions are interchangeable and serve the same purpose. You can use either one to define a test case.

For example:

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

expect Function:

The expect function is used to make assertions about the code’s behavior. It takes the actual value and returns an object with methods to make assertions about the value.

javascript
	expect(actualValue).toBe(expectedValue);

For example:

javascript
	expect(add(1, 2)).toBe(3);