Sobes.tech
Middle+

What unit tests would you write for the FizzBuzz function?

sobes.tech AI

Answer from AI

For the FizzBuzz function, the following unit tests should be written:

  1. Check division by 3: for input values divisible by 3, the function returns "Fizz".
  2. Check division by 5: for input values divisible by 5, the function returns "Buzz".
  3. Check division by 15: for input values divisible by 15, the function returns "FizzBuzz".
  4. Check numbers not divisible by 3 or 5: the function returns the string representation of the number.
  5. Check boundary values, such as 0 or negative numbers, if the function supports them.

Example in JavaScript:

function fizzBuzz(n) {
  if (n % 15 === 0) return "FizzBuzz";
  if (n % 3 === 0) return "Fizz";
  if (n % 5 === 0) return "Buzz";
  return n.toString();
}

test('returns Fizz for multiples of 3', () => {
  expect(fizzBuzz(3)).toBe('Fizz');
  expect(fizzBuzz(6)).toBe('Fizz');
});

test('returns Buzz for multiples of 5', () => {
  expect(fizzBuzz(5)).toBe('Buzz');
  expect(fizzBuzz(10)).toBe('Buzz');
});

test('returns FizzBuzz for multiples of 15', () => {
  expect(fizzBuzz(15)).toBe('FizzBuzz');
  expect(fizzBuzz(30)).toBe('FizzBuzz');
});

test('returns number as string for other numbers', () => {
  expect(fizzBuzz(7)).toBe('7');
  expect(fizzBuzz(8)).toBe('8');
});