Skip to content

Hostname is not configured under images in your next.config.js when running tests with Jest #21549

@AustinShelby

Description

@AustinShelby

What version of Next.js are you using?

10.0.2

What version of Node.js are you using?

14.2.0

What browser are you using?

Chrome

What operating system are you using?

Ubuntu

How are you deploying your application?

next start

Describe the Bug

When using Jest to test a component that uses Image from next/image you will get an error that your src prop hostname is not configured under images in your next.config.js even if you have mocked the config to include the domain.

Expected Behavior

Jest mocking should work.

To Reproduce

Testing this component:

import React from "react";
import Image from "next/image";

export const Github: React.FC = () => {
  return (
    <div>
      <Image
        width={800}
        height={600}
        sizes="600px"
        layout="responsive"
        objectFit="cover"
        src={`${process.env.NEXT_PUBLIC_CDN_URL}/hello.jpg`}
      />
      Hello World
    </div>
  );
};

with this test:

import React from "react";
import { screen, render, waitFor } from "@testing-library/react";
import { Github } from "../../../../components/github";

jest.mock("next/config", () => {
  return () => ({
    publicRuntimeConfig: {
      images: {
        domains: ["cdn.example.com"],
      },
    },
  });
});

describe("github issue reproduction", () => {
  jest.useFakeTimers("modern");
  jest.setSystemTime(new Date(2021, 1, 20, 12, 0, 0, 0));

  it("github issue", async () => {
    render(<Github />);

    await waitFor(() =>
      expect(screen.getByText("Hello World")).toBeInTheDocument()
    );
  });
});

with this jest.config.js:

module.exports = {
  moduleNameMapper: {
    "\\.(css|less)$": "identity-obj-proxy",
  },
  setupFiles: ["<rootDir>/__tests__/setupEnvironment.js"],
};

with this setupEnvironment.js:

process.env.NEXT_PUBLIC_CDN_URL = "https://cdn.example.com";

will get you this error:

    Invalid src prop (https://cdn.example.com/hello.jpg) on `next/image`, hostname "cdn.example.com" is not configured under images in your `next.config.js`
    See more info: https://err.sh/next.js/next-image-unconfigured-host

      20 |     render(<Github />);
      21 | 
    > 22 |     await waitFor(() =>
         |           ^
      23 |       expect(screen.getByText("Hello World")).toBeInTheDocument()
      24 |     );
      25 |   });

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIssue was opened via the bug report template.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions