此文件被视为 ES 模块,因为它具有“.js”文件扩展名

This file is being treated as an ES module because it has a '.js' file extension

现在我想使用jtest在typescript(Node版本v16.13.2)项目中做一个单元测试,首先我安装了jtest"jest": "^27.5.1"。添加 jest.config.js 文件:

module.exports = {
    roots: [
        "<rootDir>/test"
    ],
    testRegex: 'test/(.+)\.test\.(jsx?|tsx?)$',
    transform: {
        "^.+\.tsx?$": "ts-jest"
    },
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};

添加测试条目:

import DeviceHandler from "@utils/data/DeviceHandler";

test('hello world test', () => {
    let deviceId = DeviceHandler.getDeviceId();
    expect(deviceId).toBe("xxxx");
});

但是当我 运行 测试命令 yarn test:

ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/dolphin/source/reddwarf/frontend/js-wheel/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///Users/dolphin/source/reddwarf/frontend/js-wheel/jest.config.js:1:1
    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async requireOrImportModule (/Users/dolphin/source/reddwarf/frontend/js-wheel/node_modules/jest-util/build/requireOrImportModule.js:65:32)
    at async readConfigFileAndSetRootDir (/Users/dolphin/source/reddwarf/frontend/js-wheel/node_modules/jest-config/build/readConfigFileAndSetRootDir.js:132:22)
    at async readConfig (/Users/dolphin/source/reddwarf/frontend/js-wheel/node_modules/jest-config/build/index.js:233:18)
    at async readConfigs (/Users/dolphin/source/reddwarf/frontend/js-wheel/node_modules/jest-config/build/index.js:420:26)
    at async runCLI (/Users/dolphin/source/reddwarf/frontend/js-wheel/node_modules/@jest/core/build/cli/index.js:132:59)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
(base) 

PS:这是DeviceHandler.ts内容:

const DeviceHandler = {
    getDeviceId: async() : Promise<string> => {
        return new Promise((resolve, reject) => {
            resolve("xxxx");
        });
    },
    getDeviceIdEnhance: async (): Promise<string> => {
        return new Promise((resolve, reject) => {
            // Initialize an agent at application startup.
            const fpPromise = require('@fingerprintjs/fingerprintjs').load();
            // Get the visitor identifier when you need it.
            fpPromise
                .then((fp: { get: () => any; }) => fp.get())
                .then(async (result: { visitorId: any; }) => {
                    // This is the visitor identifier:
                    const deviceId = result.visitorId;
                    resolve(deviceId);
                });
        });
    }
};

export default DeviceHandler;

为什么会出现这个错误?我应该怎么做才能使单元测试正常工作?

您的 package.json 文件中可能有 "type": "module"。如果您删除它,它将解决此问题。

或者,如果您想保留 "type": "module",您可以将 jest.config.js 转换为 jest.config.json(and/or 如果您有 babel.config.js也需要将那个转换为 babel.config.json)。请注意,您实际上必须将其转换为 JSON 格式(因此,从中删除 module.exports = 等)。

This example project 对这一切进行了更深入的探讨