smartyfy.mrindigi.com

Web Development Pro | Lesson 042 | Unit Tests for Pure Functions

Web Development Pro · Lesson 42 of 60

Module 5: Quality, accessibility, and security

In this lesson

Prerequisites and learning outcomes

Complete lesson 41 first. This lesson builds on assertions, boundaries, and regression cases. By the end, you can write deterministic tests for event filters and data validation. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Give a test one clear responsibility

A unit test examines a small contract, ideally with explicit inputs and an observable result. Our event directory needs a filter that combines a text query and a category. The function should return a new array, retain the original record objects, and never change the supplied array. Decide these rules before choosing test values.

A test has three readable parts: arrange the fixture, act by calling the function, and assert the expected outcome. A failure should identify the broken behavior. “Combined category and query returns only repair-1” is more diagnostic than “test three.” Keep fixtures small enough that a learner can work out the answer without running the program.

Separate selection from browser state

export function selectEvents(events, { query = '', category = 'all' } = {}) {
  const needle = query.trim().toLowerCase();
  return events.filter(event =>
    (category === 'all' || event.category === category) &&
    event.title.toLowerCase().includes(needle)
  );
}

This function does not read an input element, current time, localStorage, or the network. The caller supplies all relevant information. That makes a failing case repeatable. It also lets a future interface call the same calculation without duplicating its rules. Pure calculations are especially useful seams between data handling and rendering.

The category and query conditions are joined with AND. Using OR would show every repair event even when its title did not match, and every matching title even when its category was wrong. A fixture needs both kinds of near match to detect that mistake. Testing only one perfect match can leave a faulty OR implementation unnoticed.

Use assertions that inspect meaning

The examples use Node's built-in test runner and strict assertions, with no installation or remote service. Save modules with the .mjs extension so their import/export meaning is explicit. From the example folder, run node --test select.test.mjs. The command exits unsuccessfully if an assertion fails, which makes it useful in repeatable local checks.

import test from 'node:test';
import assert from 'node:assert/strict';
import { selectEvents } from './select.mjs';
test('empty input remains empty', () => {
  assert.deepEqual(selectEvents([], { query: 'bike' }), []);
});

Use deepEqual for the contents of arrays or records. Two separately created arrays are different references even if they contain identical values. Use equal when identity itself is part of the contract. For example, selected[0] can be the exact original event object, while selected must be a different outer array.

Cover boundaries rather than collecting test counts

Include an empty collection, empty query, padded uppercase query, unknown category, and a combined filter. Check a genuine no-match result. If capacity validation accepts whole numbers from zero through fifty, test zero, fifty, negative one, fifty-one, a fraction, and a numeric string. Values immediately around a boundary reveal mistakes that a middle value cannot.

The supplied validator only answers whether one capacity fits this deliberately small contract. It is not a complete event validator. Naming it validCapacity avoids suggesting that title, identity, and venue have also been checked. A real boundary validator should report useful reasons and validate the complete record before handing it to selection logic.

Avoid assertions that merely restate the implementation. Computing an expected result with the same filter expression can reproduce the same bug on both sides. Write the expected identifiers explicitly. Similarly, do not copy the function's output into a fixture without reviewing whether it satisfies the requirement.

Check promises about unchanged inputs

Capture the input before selection and compare it afterward. A filter is not supposed to reorder the source array. The example freezes each simple record and the outer array, then checks the expected output. Freezing is shallow unless nested objects are frozen too; understand what protection your fixture actually provides.

For nested records, test only the branches that the function is allowed to change. An immutable update might create one new venue object while preserving unrelated references. A deep comparison can establish values; an identity assertion establishes whether two references point to the same object. These are different questions, and both may matter.

Keep tests deterministic and maintainable

Do not depend on a live public endpoint for a unit test. A network outage is not evidence that your filter is wrong. Supply fixed data, and test request handling separately with controlled responses. If time matters, pass a chosen timestamp rather than reading the actual clock inside the calculation.

An intentionally failing assertion can help you verify that the test runner is genuinely executing a file. Restore the correct expectation afterward and record the final passing run. Never leave a failing demonstration mixed into a suite described as passing. Keep exploratory mistakes separate from the final regression evidence.

These tests establish the specific calculation and validation cases they execute. They do not establish accessibility, visual layout, browser compatibility, or correct server configuration. A good testing strategy gives each layer a suitable check rather than trying to turn one unit suite into a certificate for the entire site.

Worked practice

Worked exercise 1: Catch an OR mistake

Task: Your query is bike and category is repair. Fixtures include a repair bike, a gardening bike, and a repair chair. Worked answer: expect only the repair bike. The other two each satisfy one condition and expose an accidental OR where the contract requires both conditions.

Worked exercise 2: Test a numeric boundary

Task: Capacity must be an integer from zero to fifty. Worked answer: include zero and fifty as accepted endpoints; reject negative one, fifty-one, 2.5, and “12”. Rejecting a numeric string keeps the boundary explicit rather than silently coercing outside data.

Worked exercise 3: Detect mutation

Task: A refactor sorts the original array before filtering. Worked answer: preserve a before snapshot and assert the original order after the call, or use a frozen fixture that throws when sorted. The returned records looking correct does not excuse violating the unchanged-input contract.

Knowledge check

Question 1

Why pass query as an argument? A) It prevents the caller from providing an invalid query. B) It removes hidden dependence on a browser control. C) It automatically validates all data. D) It makes every call return the same result.

Check question 1: answer and explanation

Answer: B. Explicit inputs make a case reproducible and reusable.

Question 2

Which fixture best tests combined filters? A) Only a record matching both. B) Only an empty array. C) A full match plus records matching each condition separately. D) Several identical full matches.

Check question 2: answer and explanation

Answer: C. Near matches expose incorrectly combined conditions.

Question 3

Which assertion compares array contents? A) deepEqual. B) Reference equality alone. C) Checking only that both arrays have the same length. D) Checking only that their first elements match.

Check question 3: answer and explanation

Answer: A. Separate arrays can contain the same values without being the same object.

Question 4

Why test fifty-one for a maximum of fifty? A) It verifies the accepted maximum itself. B) It proves that all larger inputs will be safely converted. C) It checks the lower endpoint as well. D) It probes the rejected side of the boundary.

Check question 4: answer and explanation

Answer: D. Adjacent boundary values expose inclusive/exclusive mistakes.

Question 5

What does a passing unit suite justify? A) Every browser journey works. B) The tested contracts hold for the executed cases. C) Production data is always valid. D) The site meets every accessibility requirement.

Check question 5: answer and explanation

Answer: B. Evidence is limited to its inputs and execution layer.

Sources and further reading