react-intersection-observer: Does not recognise Vitest 2 inside `beforeAll` hook

Describe the bug A clear and concise description of what the bug is.

When trying to upgrade Vitest from 1.6 to 2.0 I’m getting these warnings:

React Intersection Observer was not configured to handle mocking.
Outside Jest and Vitest, you might need to manually configure it by calling setupIntersectionMocking() and resetIntersectionMocking() in your test setup file.

// test-setup.js
import { resetIntersectionMocking, setupIntersectionMocking } from 'react-intersection-observer/test-utils';

beforeEach(() => {
  setupIntersectionMocking(vi.fn);
});

afterEach(() => {
  resetIntersectionMocking();
});

To Reproduce Try and recreate the issue in a Codesandbox:

none yet

Expected behavior A clear and concise description of what you expected to happen.

Should detect Vitest 2 similar to Vitest 1.6

Additional context Add any other context about the problem here.

Running latest version, 9.10.3

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 23 (21 by maintainers)

Most upvoted comments

@condorheroblog should be fixed by #720 released in v9.16.0

@condorheroblog you are right. I forgot to handle global correctly in the last refactor. It’s tricky, since there isn’t a reliable way to determine if the intersectionObserver is mocked.

Hi @thebuilder.

I also encountered this problem.

Image

I didn’t turn on the global mode. I used the mockIsIntersecting function in the test file, which called the warnOnMissingSetup function. Tracing the call chain, I found that this function caused it.

function testLibraryUtil(): typeof vi | undefined {
  if (typeof vi !== "undefined") return vi;
  // @ts-expect-error We don't include the Jest types
  if (typeof jest !== "undefined") return jest;
  return undefined;
}

Because I don’t have global mode enabled, this function will return undefined and print a warning message.


This is how I use it.

vitest.config.ts@3.0.7

/// <reference types="vitest/config" />

import { defineConfig } from "vite";

export default defineConfig({
  test: {
    environment: "happy-dom",
    setupFiles: ["./tests/vitest.setup.ts"],
  },
});
  1. vitest.setup.ts
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import {
  resetIntersectionMocking,
  setupIntersectionMocking,
} from "react-intersection-observer/test-utils";
import { afterEach, beforeEach, vi } from "vitest";

beforeEach(() => {
  setupIntersectionMocking(vi.fn);
});

afterEach(() => {
  resetIntersectionMocking();
  cleanup();
});
  1. mockIsIntersecting
import { act, render, screen } from "@testing-library/react";
import React, { useState } from "react";
import { mockIsIntersecting } from "react-intersection-observer/test-utils";
import { describe, expect, it } from "vitest";

import { Scrollama, Step } from "../src";

const stepStyle = {
  border: "5px solid #cccccc",
  height: "300px",
  width: "500px",
  margin: "100px",
};

const HookComponent = () => {
  const [currentStep, setCurrentStep] = useState<number>(0);
  return (
    <div data-testid="wrapper" data-step={currentStep}>
      <Scrollama<number> debug onStepEnter={({ data }) => setCurrentStep(data)}>
        {[1, 2, 3].map((stepNumber) => (
          <Step key={stepNumber} data={stepNumber}>
            <div style={stepStyle} data-testid={`step-${stepNumber}`}>
              Step {stepNumber}
            </div>
          </Step>
        ))}
      </Scrollama>
    </div>
  );
};

describe("Scrollama", () => {
  it("should render correctly", async () => {
    render(
      <>
        <div style={{ height: window.innerHeight }} />
        <HookComponent />
        <div style={{ height: window.innerHeight }} />
      </>,
    );
    const wrapper = screen.getByTestId("wrapper");

    // Should not be updated until intersection observer triggers
    expect(wrapper).toHaveAttribute("data-step", "0");

    const step1 = screen.getByTestId("step-1");
    const step2 = screen.getByTestId("step-2");
    const step3 = screen.getByTestId("step-3");

    act(() => {
      mockIsIntersecting(step1, true);
    });
    expect(wrapper).toHaveAttribute("data-step", "1");
    act(() => {
      mockIsIntersecting(step1, false);
    });
    expect(wrapper).toHaveAttribute("data-step", "1");

    act(() => {
      mockIsIntersecting(step2, true);
    });
    expect(wrapper).toHaveAttribute("data-step", "2");
    act(() => {
      mockIsIntersecting(step2, false);
    });
    expect(wrapper).toHaveAttribute("data-step", "2");

    act(() => {
      mockIsIntersecting(step3, true);
    });
    expect(wrapper).toHaveAttribute("data-step", "3");
    act(() => {
      mockIsIntersecting(step3, false);
    });
    expect(wrapper).toHaveAttribute("data-step", "3");

    // use screen.debug() to see the DOM
    // screen.debug();
  });
});

FYI @RobinTail - I’ll drop the beforeAll in #716 It’s simply not safe to rely on just the beforeAll, since global options in test runners like mockReset can reset the observer after a test run, preventing it from working in the following.

  • Don’t run mockAllIsIntersecting in beforeAll
  • Consider using a fallback instead, to always have observers report true if they aren’t mocked.

Dear @thebuilder , here is the VM that reproduces the issue:

https://codesandbox.io/p/devbox/crimson-night-w64sxn

In terminal try to execute yarn test.

(you may probably need to be logged in for that)

I’ll try to prepare a sandbox to reproduce it

#690 The tests using the test-utils in the library are all running fine after upgrading.