DEV Community

Jakub Jadczyk
Jakub Jadczyk

Posted on

How to write unit test in jest.

In this post I will show nice way to create unit test in jest.js.

Create test file first and describe all possible scenarios.

In this case we have 3 scenarios. We just describe how the test looks like without any knowledge about our function.

import { short } from "./short";

describe("short", () => {
  test("If array length < 3 should return array without modification", () => {
    const result = short(["1", "2"]);
    expect(result).toBe(result);
  });

  test("If array length > 3 Should return just first 3 elements of an array if there is no 2nd argument", () => {
    const result = short(["1", "2", "3", "4"]);
    expect(result).toBe(["1", "2", "3"]);
  });

  test("Should consider 2nd argument as a number which describe how long an array could be", () => {
    const result = short(["1", "2", "3", "4"], 2);
    expect(result).toBe(["1", "2"]);
  });
});

Enter fullscreen mode Exit fullscreen mode

Create function that will cover the tests scenarios.

Right now we can create function remembering about the tests we previously described.

const short = (array, number) => {
  if (number) return array.splice(0, number);

  return array.length < 3 ? array : array.splice(0, 3);
};

export default short;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)