Next.js Discord

Discord Forum

Configure Jest with Next and shared types

Unanswered
Red wood ant posted this in #help-forum
Open in Discord
Avatar
Red wood antOP
Hello I'm trying to setup jest with next to allow types from outside the nextjs directory.

The directory structure is as follows:

/
- web-next/ (next project)
- shared/   (shared types)


Jest outputs "module not found" when in one of the tests I use a function that imports from shared/

Example of such file

// service/parse/parsers.ts

import {
    Character
} from "@/shared/v1/common_pb";

const ch = {
    ...
} satisfies Character;


---

I have the following jest setup

import type { Config } from "jest";
import nextJest from "next/jest.js";

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

const config: Config = {
    testPathIgnorePatterns: ["/node_modules/", "/e2e/"],
    ...
    moduleNameMapper: {
        "^@shared/(.*)$": path.resolve(
        __dirname,
        "../../shared/ts/connect/galatea/v1",
    ),
    }
};

export default createJestConfig(config);


With the following next config that's configured to allow types from the shared dir:

/** @type {import("next").NextConfig} */
const nextConfig = {
    ...
    webpack: (config, options) => {
        config.resolve = {
            ...config.resolve,
            extensionAlias: {
                ".js": [".ts", ".js"],
            },
        };

        // transpile shared/ts/connect/g/v1
        config.module.rules.push({
            test: /\.ts$/,
            use: [options.defaultLoaders.babel],
            include: path.resolve(__dirname, "../../shared/ts/connect/g/v1"),
        });

        return config;
    },
        ...
}

0 Replies