1

I am not able to load my next.config file in Jest for tests. I am testing the submit function in a form which calls a server action.

Form

const Form = ({ mockSubmit }: { mockSubmit: () => void }) => {
 const handleSubmit = async (data) => {
  apiCall(data); //Server action
 };

 return (
  <form onSubmit={handleSubmit}>
   <input name="name" />
   <button type="submit">Submit</button>
  </form>
 );
};

Form.test

describe('Create form', () => {
  it('should validate form fields', async () => {
    const mockSubmit = jest.fn();
    const { user } = userEventsTestSetup(
      <Form mockSubmit={mockSubmit}/>
    );
    await user.type(screen.getByRole('textbox', { name: 'name' }), 'ABCD');
    expect(mockSubmit).not.toHaveBeenCalled();
  });
});

jest.setup.ts

jest.mock('next/config', () => () => ({
  publicRuntimeConfig: {
    experimental: {
     typedRoutes: true,
     serverActions: true,
   },
  },
}));

jest.config

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});

const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '^@/pages/(.*)$': '<rootDir>/pages/$1',
  },
  testEnvironment: 'jest-environment-jsdom',
};

module.exports = createJestConfig(customJestConfig);

Despite initializing next config in my jest.setup, I still get this error:

To use Server Actions, please enable the feature flag in your Next.js config. Read more: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#convention

Re-Angelo
  • 217
  • 3
  • 15

1 Answers1

0

Mock next/config in the Test Setup File: In your jest.setup.js file, make sure to mock the next/config module properly. Update the mocking to return the expected config structure:

jest.mock('next/config', () => {
    const originalConfig = jest.requireActual('next/config');
    return () => ({
    ...originalConfig(),
    publicRuntimeConfig: {
        experimental: {
        typedRoutes: true,
        serverActions: true,
        },
    },
    });
});

then, ensure Proper Module Resolutions: Make sure that your custom Jest configuration (in your jest.config.js file) is correctly set up to resolve modules using your project's root directory () for proper module resolution. Ensure that the paths you're using for mocking modules in your test are accurate.

Mohamed Mostafa
  • 520
  • 2
  • 10
  • I followed your example but still get the same issue. I see there was someone with the same issue opened on github: https://github.com/vercel/next.js/issues/53065 Thanks still for your help! – Re-Angelo Aug 07 '23 at 12:23