Unit testing with React and Jest

Hello guys!

Thanks for your amazing work and especially for the React wrapper around Moralis.

I have a plain vanilla React app that I would like to unit test.

What is the good approach to to the following?

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

jest.mock("react-moralis"); // I tried to mock MoralisProvider

it("should render the app", () => {
      <App />
  const linkElement = screen.getByText(/Hello world/i);

If I do not wrap the App, I get this error.

it("should render the app", () => {
  render(<App />);
  const linkElement = screen.getByText(/Hello world/i);

  ● should render the app

    TypeError: Cannot destructure property 'authenticate' of '(0 , _reactMoralis.useMoralis)(...)' as it is undefined.

      14 |
      15 | const App = () => {
    > 16 |   const { authenticate, logout, isAuthenticated, user } = useMoralis();
1 Like

Hi. The correct approach would be to render the App or component with a valid MoralisProvider. So the first example is correct.


  1. You could provide a MoralisProvider with the appId+serverUrl that you want to use for the tests.
  2. Or: you probably can mock the Provider, but all the features inside react-moralis require the provider with a valid Moralis instance. So this route might be a lot of work, as you need to mock all the functions inside react-moralis.

I think option 1 would be the easiest, but it has a dependency that your tests are using an existing moralis server.

Sidenote: I have NOT tested any of the features in a jest environment. So I am not sure if react-moralis works correctly at all in a Jest environment.

1 Like

Thank you Erno.

Solution 1 does not work unfortunately. If you have any idea?
Edit 1: I was still mocking react-moralis in my previous post, now I am using the real implementation but have this error
Edit 2 : The error comes from the fact we assume we have a window context. (window as any).ethereum.on( I think there are ways to work around this like by injecting this ethereum parameter.

  ● should render the app

    TypeError: Cannot read property 'on' of undefined

      4 |
      5 | it("should render the app", () => {
    > 6 |   render(
        |   ^
      7 |     <MoralisProvider
      8 |       appId="xxxxxxxxxx"
      9 |       serverUrl="https://xxxxxxxxxxx.moralis.io:2053/server"

      at node_modules/react-moralis/src/hooks/useMoralis/_useMoralisAuth.ts:339:30

Solution 2 looks challenging, it’s true :slight_smile:

I just updated react-moralis from 0.1.2 to 0.1.6. I noticed the change about the window object.
It works now. :slight_smile:

1 Like