What error is this: “Jest encountered an unexpected token”? It came from “isPortReachable” import of my code to be tested

Im trying to do Jest testing for all my domain/service/business logic of my web app.

One of the import was isPortReachable, and Conf, but apparently every file with this import would fail the test suite with a super long error message. Im not sure what this error mean.

Error message from Jest:

 FAIL  src/__test__/systemControl.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /workspaces/ITP_G20/node_modules/is-port-reachable/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import net from 'node:net';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      4 | import {editHostIpSchema, powerLevelSchema} from "@/schema/custom";
      5 | import {z} from "zod";
    > 6 | import isPortReachable from "is-port-reachable";
        | ^
      7 | import Conf from "conf";
      8 |
      9 | const config = new Conf({projectName: 'SIT-RFID-System'});

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
      at Object.<anonymous> (src/domain/systemControl.ts:6:1)
      at Object.<anonymous> (src/__test__/systemControl.test.ts:7:1)

This is my code to be tested

"use server";

import {addSystemStatus, getLatestSystemStatus} from "@/data/local/systemStatusRepo";
import {editHostIpSchema, powerLevelSchema} from "@/schema/custom";
import {z} from "zod";
import isPortReachable from "is-port-reachable";
import Conf from "conf";

const config = new Conf({projectName: 'SIT-RFID-System'});

/**
 * Retrieves the system status by calling the getLatestSystemStatus function.
 * @returns A promise that resolves to the latest system status.
 */
export async function retrieveSystemStatus() {
    const latestStatus = await getLatestSystemStatus();
    if (!latestStatus) {
        return logStatusChange(false);
    }
    return latestStatus;
}

/**
 * Logs the status change of the system.
 * @param status - The new status of the system.
 * @returns A promise that resolves with the result of adding the system status.
 */
export async function logStatusChange(status: boolean) {
    const systemStatusData = {
        systemStatus: status,
        systemTime: new Date()
    };
    console.log(systemStatusData);
    return await addSystemStatus(systemStatusData);
}

export async function getHostIpConfig(){
    return config.get('hostIp') as string | undefined;
}

export async function setHostIpConfig(value: z.infer<typeof editHostIpSchema>){
    const validatedFields = editHostIpSchema.safeParse(value);
    if (!validatedFields.success) {
        return {error: "Invalid fields!"};
    }

    const {ip} = validatedFields.data;

    const ipPortReachable = await isPortReachable(1883, {host: ip});

    if (!ipPortReachable) {
        return {error: "IP Address is not reachable!"};
    }
    
    config.set('hostIp', ip);
}

export async function setPowerLevelConfig(value: z.infer<typeof powerLevelSchema>){
    const validatedFields = powerLevelSchema.safeParse(value);
    if (!validatedFields.success) {
        return {error: "Invalid fields!"};
    }

    const powerLevel = validatedFields.data;

    config.set('powerLevel', powerLevel);
}

export async function getPowerLevelConfig(){
    return config.get('powerLevel') as z.infer<typeof powerLevelSchema> | undefined;
}

This is my test.ts file

import React from "react";
import test from "node:test";
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";

import {
    retrieveSystemStatus,
    logStatusChange,
    getHostIpConfig,
} from "../domain/systemControl";
import { getLatestSystemStatus, addSystemStatus } from "../data/local/systemStatusRepo";
import { SystemStatus } from "@prisma/client";
import Conf from "conf";

const config = new Conf({ projectName: 'SIT-RFID-System' });

jest.mock("@/data/local/systemStatusRepo", () => ({
    getLatestSystemStatus: jest.fn(),
    addSystemStatus: jest.fn()
}));

jest.mock("conf");

describe("retrieveSystemStatus", () => {
    it("should retrieve the latest system status", async () => {
        const latestStatus: SystemStatus = { id: "1", systemStatus: true, systemTime: new Date() };

        (getLatestSystemStatus as jest.Mock).mockReturnValueOnce(latestStatus);

        const result = await retrieveSystemStatus();

        expect(getLatestSystemStatus).toHaveBeenCalled();
        expect(result).toEqual(latestStatus);
    });

    it("should log status change if no latest status is found", async () => {
        (getLatestSystemStatus as jest.Mock).mockReturnValueOnce(null);
        const statusChange: SystemStatus = { id: "2", systemStatus: false, systemTime: new Date() };

        (addSystemStatus as jest.Mock).mockReturnValueOnce(statusChange);

        const result = await retrieveSystemStatus();

        expect(getLatestSystemStatus).toHaveBeenCalled();
        expect(addSystemStatus).toHaveBeenCalledWith({ systemStatus: false, systemTime: expect.any(Date) });
        expect(result).toEqual(statusChange);
    });
});

describe("logStatusChange", () => {
    it("should log the status change of the system", async () => {
        const statusChange: SystemStatus = { id: "1", systemStatus: true, systemTime: new Date() };

        (addSystemStatus as jest.Mock).mockReturnValueOnce(statusChange);

        const result = await logStatusChange(true);

        expect(addSystemStatus).toHaveBeenCalledWith({ systemStatus: true, systemTime: expect.any(Date) });
        expect(result).toEqual(statusChange);
    });
});

describe("getHostIpConfig", () => {
    it("should retrieve the host IP configuration", async () => {
        const hostIp = "192.168.1.1";
        (config.get as jest.Mock).mockReturnValue(hostIp);

        const result = await getHostIpConfig();

        expect(config.get).toHaveBeenCalledWith('hostIp');
        expect(result).toEqual(hostIp);
    });
});

I tried to change my jest config to a solution i found online, but it doesnt solve it

/**
 * For a detailed explanation regarding each configuration property, visit:
 * https://jestjs.io/docs/configuration
 */

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

const config: Config = {
  // All imported modules in your tests should be mocked automatically
  // automock: false,

  // Stop running tests after `n` failures
  // bail: 0,

  // The directory where Jest should store its cached dependency information
  // cacheDirectory: "/tmp/jest_rs",

  // Automatically clear mock calls, instances, contexts and results before every test
  clearMocks: true,

  // Indicates whether the coverage information should be collected while executing the test
  collectCoverage: true,

  // An array of glob patterns indicating a set of files for which coverage information should be collected
  // collectCoverageFrom: undefined,

  // The directory where Jest should output its coverage files
  coverageDirectory: "coverage",

  // An array of regexp pattern strings used to skip coverage collection
  // coveragePathIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // Indicates which provider should be used to instrument code for coverage
  coverageProvider: "v8",

  // A list of reporter names that Jest uses when writing coverage reports
  // coverageReporters: [
  //   "json",
  //   "text",
  //   "lcov",
  //   "clover"
  // ],

  // An object that configures minimum threshold enforcement for coverage results
  // coverageThreshold: undefined,

  // A path to a custom dependency extractor
  // dependencyExtractor: undefined,

  // Make calling deprecated APIs throw helpful error messages
  // errorOnDeprecated: false,

  // The default configuration for fake timers
  // fakeTimers: {
  //   "enableGlobally": false
  // },


  // Force coverage collection from ignored files using an array of glob patterns
  // forceCoverageMatch: [],

  // A path to a module which exports an async function that is triggered once before all test suites
  // globalSetup: undefined,

  // A path to a module which exports an async function that is triggered once after all test suites
  // globalTeardown: undefined,

  // A set of global variables that need to be available in all test environments
  // globals: {},

  // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
  // maxWorkers: "50%",

  // An array of directory names to be searched recursively up from the requiring module's location
  // moduleDirectories: [
  //   "node_modules"
  // ],

  // An array of file extensions your modules use
  // moduleFileExtensions: [
  //   "js",
  //   "mjs",
  //   "cjs",
  //   "jsx",
  //   "ts",
  //   "tsx",
  //   "json",
  //   "node"
  // ],

  // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
  moduleNameMapper: { "^@/(.*)$": "<rootDir>/src/$1" },

  // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
  // modulePathIgnorePatterns: [],

  // Activates notifications for test results
  // notify: false,

  // An enum that specifies notification mode. Requires { notify: true }
  // notifyMode: "failure-change",

  // A preset that is used as a basef for Jest's configuration
  preset: 'ts-jest',

  // Run tests from one or more projects
  // projects: undefined,

  // Use this configuration option to add custom reporters to Jest
  // reporters: undefined,

  // Automatically reset mock state before every test
  // resetMocks: false,

  // Reset the module registry before running each individual test
  // resetModules: false,

  // A path to a custom resolver
  // resolver: undefined,

  // Automatically restore mock state and implementation before every test
  // restoreMocks: false,

  // The root directory that Jest should scan for tests and modules within
  // rootDir: undefined,

  // A list of paths to directories that Jest should use to search for files in
  // roots: [
  //   "<rootDir>"
  // ],

  // Allows you to use a custom runner instead of Jest's default test runner
  // runner: "jest-runner",

  // The paths to modules that run some code to configure or set up the testing environment before each test
  // setupFiles: [],

  // A list of paths to modules that run some code to configure or set up the testing framework before each test
  // setupFilesAfterEnv: [],

  // The number of seconds after which a test is considered as slow and reported as such in the results.
  // slowTestThreshold: 5,

  // A list of paths to snapshot serializer modules Jest should use for snapshot testing
  // snapshotSerializers: [],

  // The test environment that will be used for testing
  // testEnvironment: "jest-environment-node",
  testEnvironment: "jsdom",

  // Options that will be passed to the testEnvironment
  // testEnvironmentOptions: {},

  // Adds a location field to test results
  // testLocationInResults: false,

  // The glob patterns Jest uses to detect test files
  // testMatch: [
  //   "**/__tests__/**/*.[jt]s?(x)",
  //   "**/?(*.)+(spec|test).[tj]s?(x)"
  // ],

  // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
  testPathIgnorePatterns: [
    "/node_modules/"
  ],

  // The regexp pattern or array of patterns that Jest uses to detect test files
  // testRegex: [],

  // This option allows the use of a custom results processor
  // testResultsProcessor: undefined,

  // This option allows use of a custom test runner
  // testRunner: "jest-circus/runner",

  // A map from regular expressions to paths to transformers
  // transform: undefined,

  // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
  transformIgnorePatterns: [
    "/node_modules/(?!d3-(array|format|geo))",
    "\.pnp\.[^\/]+$"
  ],

  // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
  // unmockedModulePathPatterns: undefined,

  // Indicates whether each individual test should be reported during the run
  // verbose: undefined,

  // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
  // watchPathIgnorePatterns: [],

  // Whether to use watchman for file crawling
  // watchman: true,
};

export default config;

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật