npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jest-react-mock-utils

v1.1.0

Published

Simple utiltiies to help with mocking React scenarios for testing

Downloads

4

Readme

jest-react-mock-utils

CI Coverage Status npm version Downloads

Simple utiltiies to help with mocking React scenarios for testing.

Usage

The best option is to check out our integration tests to see more real world scenarios.

import { render } from "@testing-library/react";
import React from "react";
import { it, jest } from "@jest/globals";
import { createMockComponent, getMockComponentPropCalls } from "../../index.js";

// Step 1: if using typescript, import the Prop types for the child component
import type { ChildProps } from "./test-asset.child.js";

// Step 2: Now mock the child component
jest.unstable_mockModule("./test-asset.child.js", () => ({
  Child: createMockComponent<ChildProps>("button"),
}));

// Step 3: Import the parent and child, mocking the child
const { Parent, parentTestIdMap } = await import("./parent.js");
const { Child } = jest.mocked(await import("./test-asset.child.js"));

afterEach(() => {
  Child.mockClear();
});

// Step 4: Write your test
it("Child callback causes click count to increase", async () => {
  // Arrange
  const result = render(<Parent />);

  // Act - Fires the onComplicatedCallback for the last render cycle
  await act(() =>
    getMockComponentPropCalls(Child)
      ?.at(-1)
      ?.onComplicatedCallback?.({} as any)
  );

  // Assert
  const countElement = result.getByTestId("click-count");
  expect(countElement.innerHTML).toBe("1");
});

it("Clicking child causes click count to increase", async () => {
  // Arrange
  const result = render(<Parent />);

  // Act
  await userEvent.click(result.getByRole("button"));

  // Assert
  const countElement = result.getByTestId("click-count");
  expect(countElement.innerHTML).toBe("1");
});

I get an error when using await import

There's two halves to this problem:

  1. Dynamic imports (e.g. import("...")) were implemented in ES2020:
    • Does your runtime environment support this? Node started support in 13.2.0
    • If using typescript, is your module set to ES2020 or later?
  2. Top level await statements were implemented in ES2022:
    • Does your runtime environment support this? Node started support in 14.8.0.
    • If using typescript, is your module set to ES2022 or later?

Purpose

Unfortunately there exist scenarios where you may not want to render a child component; for example when that child component is delay loaded, complex, unstable, server driven, or not owned by you directly and is already covered by integration or end to end testing scenarios.

A good example scenario is Stripe's React Elements Component and Adyen's web components both of which have the following implementation details which make it difficult to test cleanly:

  • a significant amount of internal logic
  • server side driven logic
  • the use of iframes limiting access to textfields (for credit card security purposes)

To create a full integration test for this scenario would be extremely complex, costly, and constantly unpredictable as Stripe and Adyen can change the rendering of the components from their server side causing random instability of your tests.

Instead of constantly being on the backfoot and your CI breaking because another company updated their systems, mocking those dependencies provides a level of stability at the sacrifice of real world resemblance.

How is this similar/different than enzyme's shallow?

Enzyme's shallow would be able to mock all the imports for you by calling shallow(<Parent />). This library requires you to:

  1. Use jest.unstable_mockModule to mock all the child components the Parent component is dependent on
  2. Dynamically load the Parent component after mocking all the child components

Theoretically if you mocked all the children a Parent component was dependent on, it would be fairly similar to Enzyme's shallow render.

Goals

Dependencies

This project's goal is to have only two dependencies: React and Jest. This way it can be utilized by any React testing system (e.g. @testing-library/react, react-test-renderer, or other) and not tie you down to a specific testing system.