DEV Community

Jakub Jadczyk
Jakub Jadczyk

Posted on

3 2

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay