Introduction
Testing helps find mistakes early so your code works well. It makes your programs more reliable and easier to fix.
Testing helps find mistakes early so your code works well. It makes your programs more reliable and easier to fix.
import assert from 'assert'; describe('Test group name', () => { it('should do something expected', () => { const result = someFunction(); assert.strictEqual(result, expectedValue); }); });
describe groups related tests together.
it defines a single test case with a clear goal.
import assert from 'assert'; describe('Addition tests', () => { it('adds 2 + 3 to equal 5', () => { assert.strictEqual(2 + 3, 5); }); });
import assert from 'assert'; function greet(name) { return `Hello, ${name}!`; } describe('Greet function', () => { it('greets Alice correctly', () => { assert.strictEqual(greet('Alice'), 'Hello, Alice!'); }); });
This program tests the multiply function with two cases: normal numbers and zero.
import assert from 'assert'; function multiply(a, b) { return a * b; } describe('Multiply function tests', () => { it('multiplies 3 and 4 to get 12', () => { assert.strictEqual(multiply(3, 4), 12); }); it('multiplies 0 and 5 to get 0', () => { assert.strictEqual(multiply(0, 5), 0); }); });
Write small tests that check one thing at a time.
Run tests often to catch problems early.
Good tests save time and frustration later.
Testing finds errors before users do.
It helps keep your code working after changes.
Tests make your code more trustworthy and easier to improve.
test() to define tests.test() correctly with a description and a function.test('check sum', () => {
const sum = (a, b) => a + b;
expect(sum(2, 3)).toBe(5);
});toBe(5) is true, so the test passes.describe('Array test', () => {
it('should return length 3', () => {
const arr = [1, 2, 3];
if(arr.length !== 3) {
throw new Error('Length mismatch');
}
});
});expect or assert for clearer test results.Pass the test and this pattern moves unknown