1

I am trying to run a test in next.js using jest, but i keep getting an error: The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.

I have tried following the link and addding the docblock:

/**
 * @jest-environment jsdom
 */

to my code with no success.

I have also tried configuring my jest.config.js based on the next.js testing page. This does not work I have tried both the solution with and without the rust compiler. Neither works:

Package.JSON:

{
  "name": "chat",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest --env=node --forceExit --watchAll --coverage"
  },
  "dependencies": {
    "@firebase/testing": "^0.20.11",
    "firebase": "^9.9.4",
    "kill-port": "^2.0.1",
    "next": "12.2.5",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-firebase-hooks": "^5.0.3",
    "react-hot-toast": "^2.3.0",
    "uuid": "^8.3.2"
  },
  "devDependencies": {
    "@babel/plugin-syntax-jsx": "^7.18.6",
    "@babel/preset-react": "^7.18.6",
    "@firebase/rules-unit-testing": "^2.0.4",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@types/jest": "^29.0.2",
    "eslint": "8.23.0",
    "eslint-config-next": "12.2.5",
    "firebase-admin": "^11.0.1",
    "jest": "^29.0.3",
    "jest-environment-jsdom": "^29.0.3"
  }
}

Jest.config.js:

// jest.config.js
const nextJest = require('next/jest');

const createJestConfig = nextJest({
    // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
    dir: './',
});

// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const customJestConfig = {
    // Add more setup options before each test is run
    // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
    // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
    //moduleDirectories: ['node_modules', '<rootDir>/'],
    testEnvironment: 'jest-environment-jsdom',
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);

test/page.test.js

import { render, screen } from '@testing-library/react';
import Home from '../pages/index';

describe('Home', () => {
    it('renders a heading', () => {
        render(<Home />);
        expect(2 + 2).toBe(4);
    });
}); 

1 Answer 1

2

You're overriding the env in your npm test script, remove --env=node:

"test": "jest --forceExit --watchAll --coverage"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.