DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

Errors I encountered during Jest testing and how to fix them

Introduction

This article summarizes the errors and solutions I encountered when using Jest to test a "learning log app" built using React, TypeScript, Chakra UI, and Supabase.

1. supabaseUrl is required.

Situation:

I accidentally called a client for an external service (Supabase, Firebase, etc.) during testing, and an error occurred because .env was missing.

Cause:

The real client was used when Jest was executed. The mock was not applied.

Solution:

Create src/mocks/supabase.ts to mock it.

export const superbase = {
from: () => ({
select: async () => ({ data: [], error: null }),
insert: async () => ({ error: null }),
delete: async () => ({ error: null }),
update: async () => ({ error: null }),
}),
};
Enter fullscreen mode Exit fullscreen mode

Additionally, set moduleNameMapper in jest.config.js to ensure that mocks are used.

2. Warning: Received NaN for the 'value' attribute

Situation:

A warning occurred when NaN was passed to the Chakra UI NumberInput.

Cause:

The connection between the React Hook Form Controller and the numeric input was incomplete, causing the string-to-number conversion to be broken.

Solution:

  • Set valueAsNumber: true in the Controller to treat it as a number.

  • Always set defaultValue to 0 or 1 to specify the initial value.

3. Unable to find element by text

Situation:

Text matching failed.

Cause:

The actual UI text was different (e.g., the implementation was "Study Record," but the test was looking for "Study Record App").

The validation error message text was inconsistent with the implementation.

Solution:

Modify the test code to match the UI.

expect(await screen.findByText(/Study Record/i)).toBeInTheDocument();
expect(await within(dialog).findByText(/time must be 1 or greater/i)).toBeInTheDocument();
Enter fullscreen mode Exit fullscreen mode

Modify the test to match the actual UI display.

4. Test Suites: 0 of 1 total (Stuck on RUNS)

Situation:

The test is stuck on "RUNS."

Cause:

The real Supabase client was being called repeatedly, causing an infinite loop.

The mock was not being applied correctly.

Solution:

  • Always include jest.mock("../utils/supabase"); at the beginning of your test file.

  • Prepare mocks/supabase.ts and always use mocks when testing.

Summary

This took a while.

Top comments (0)