Next.js Discord

Discord Forum

How to make environment variables be recognized for tests with Jest?

Answered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
I followed this link's instructions
https://nextjs.org/docs/app/building-your-application/testing/jest
to set up jest in my next.js project. I'm at a point where the test runner doesn't seem to recognize environment variables from a file. I don't know why would it need to, as this should be a simple unit test for a component (I'm just starting out testing).

It says:
    Your project's URL and Key are required to create a Supabase client!

    Check your Supabase project's API settings to find these values

    https://supabase.com/dashboard/project/_/settings/api

      1 | import { createBrowserClient } from '@supabase/ssr'
      2 |
> 3 | export const supabase = createBrowserClient(
        |                                            ^
      4 |   process.env.NEXT_PUBLIC_SUPABASE_URL!,
      5 |   process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
      6 | )


I followed phind's instructions on installing @next/env package, create a test.env.js file with the contents:
import { loadEnvConfig } from '@next/env';
import { resolve } from 'path';

export default async () => {
  const projectDir = process.cwd();
  loadEnvConfig(projectDir);
};

and in my jest.config.js i added:
globalSetup: '<rootDir>/test.env.js

it says:
This setup ensures that your environment variables are loaded before your tests run, making them available to your components and tests as expected.
The error stayed though.
Answered by Asian black bear
SOLVED: the solution was to follow the instructions under the section Environment variables in this article: https://medium.com/@qhphan5/integration-tests-with-jest-in-next-js-supabase-project-00cc23688aa2
View full answer

2 Replies

Asian black bearOP
for reference, my test file (the only one):

import LayoutAddNew from "@/app/components/admin/LayoutAddNew"
import { render, screen } from "@testing-library/react"

describe('Admin: LayoutAddNew', () => {

  it('contains ADD NEW button', () => {
    render(<LayoutAddNew />)

    const button = screen.getByText(/add new/i)

    expect(button).toBeInTheDocument()
  })
})
Asian black bearOP
SOLVED: the solution was to follow the instructions under the section Environment variables in this article: https://medium.com/@qhphan5/integration-tests-with-jest-in-next-js-supabase-project-00cc23688aa2
Answer