DEV Community

Chaima Bouchareb
Chaima Bouchareb

Posted on

Unit testing example

We have a function called capitalize that takes a string and makes the first letter uppercase

function capitalize(str) {
  if (!str) return str;
  return str[0].toUpperCase() + str.slice(1);
}

module.exports = capitalize;
Enter fullscreen mode Exit fullscreen mode

To perform the unit test for this function, we can use the following tests:

const capitalize = require('./capitalize');

test('capitalizes the first letter', () => {
  expect(capitalize('hello')).toBe('Hello');
});

test('leaves an already-capitalized string unchanged', () => {
  expect(capitalize('World')).toBe('World');
});

test('handles a single character', () => {
  expect(capitalize('a')).toBe('A');
});

test('returns empty string for empty input', () => {
  expect(capitalize('')).toBe('');
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)