Testing Documentation for helpers.ts

This document provides guidance on writing testable functions, creating corresponding test files, running tests with "vitest," and integrating tests into GitHub Actions for Continuous Integration (CI) / Continuous Deployment (CD) workflows.

This guide covers the process of writing testable functions, creating test files, running tests with "vitest," and integrating tests into GitHub Actions for Continuous Integration (CI) / Continuous Deployment (CD) workflows.

The project is configured with GitHub Actions for CI/CD, which runs whenever changes are pushed to the main branch. Essential dependencies, including "vitest," are set up to automatically execute tests and maintain code quality. The status of workflow runs can be monitored in the "Actions" tab of the GitHub repository. For custom configurations, the .github/workflows directory contains the existing configuration files.

GitHub Actions Dashboard

Above is an image of the GitHub Actions dashboard where you can monitor the status of workflow runs.

When writing functions, aim for purity as they are easier to test due to their dependence on input parameters and deterministic output. Minimizing side effects within functions simplifies testing and results in more predictable behavior. Dependency injection is recommended to provide dependencies explicitly to functions, aiding in mocking or replacing dependencies during testing.

Writing Test Files

1. Create a Test File

  • Create a test file with a naming convention like <filename>.test.ts. For example, helpers.test.ts.

2. Example Test Case

// helpers.test.ts
import { expect, test } from 'vitest';
import { toDateTime } from './helpers';
 
test('helpers: toDateTime should return a date object', () => {
  // Arrange
  const date = new Date();
 
  // Act
  const dateObject = toDateTime(date.getTime());
 
  // Assert
  expect(dateObject).toBeInstanceOf(Date);
});

In this example:

  • Arrange: Set up the necessary preconditions, such as creating a Date object.
  • Act: Perform the action being tested, such as calling the toDateTime function with a specific input.
  • Assert: Verify that the outcome matches the expected result, using assertions provided by the testing framework.

Running Tests with "vitest"

  1. Run tests locally:
yarn test

This command executes the test suite and provides feedback on the test results, helping you identify and address any issues.