DEV Community

Monica Granbois
Monica Granbois

Posted on • Originally published at monicagranbois.com

3

How to mock nanoid

This short blog post describes how to use Jest to mock nanoid. The nanoid function generates a unique string id. I used it to generate an id for an object. However, I wanted a stable id when unit testing the code. To accomplish this, I mocked the nanoid module and function by doing the following:

jest.mock("nanoid", () => {
  return { nanoid: () => "1234" };
});
Enter fullscreen mode Exit fullscreen mode

The above code does the following:

  • jest.mock("nanoid"...) - This part mocks the nanoid module.
  • return { nanoid: () => "1234" }; - This part mocks the nanoid function. "1234" is returned when the nanoid function is called.

Below, is a simple example of a React app using the nanoid function and a unit test mocking it.

App.js

import { nanoid } from "nanoid";

class Item {
  constructor(name, price) {
    this.id = nanoid();  //use nanoid to generate a unique id
    this.name = name;
    this.price = price;
  }
}

function Display({ item }) {
  return (
    <div>
      <h2>Item</h2>
      <p>id: {item.id}</p>
      <p>name: {item.name}</p>
      <p>price: {item.price}</p>
    </div>
  );
}

function App() {
  const item = new Item("apple", 2);
  return (
    <div className="App">
      <h1>Nanoid Unit Test Example</h1>
      <Display item={item} />
    </div>
  );
}

export default App;
export { Display, Item };
Enter fullscreen mode Exit fullscreen mode

App.test.js

import { render, screen } from "@testing-library/react";
import { Display, Item } from "./App";

jest.mock("nanoid", () => {
  return { nanoid: () => "1234" };
});

describe("test the Display", () => {
  it("should display the item info", () => {
    let item = new Item("Orange", 5);
    render(<Display item={item} />);
    expect(screen.getByText(/id: 1234/i)).toBeInTheDocument();
    expect(screen.getByText(/name: Orange/i)).toBeInTheDocument();
    expect(screen.getByText(/price: 5/i)).toBeInTheDocument();
  });
});
Enter fullscreen mode Exit fullscreen mode

Note: As of this writing CodeSandbox does not support Jest mocks.

References:

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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