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

Dol*_*hin 23 unit-testing typescript

现在我想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'],
};
Run Code Online (Sandbox Code Playgroud)

添加测试条目:

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

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

但是当我运行测试命令时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) 
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

为什么会发生这个错误?我应该怎么做才能使单元测试工作?

cmc*_*loh 54

"type": "module"你的档案里可能有package.json。如果删除它就会解决这个问题。

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

这个示例项目对这一切进行了更深入的探讨

  • 这非常有帮助!谢谢。您还可以在 jest 和 babel 配置文件中使用 `module.exports =`,将它们重命名为 `jest.config.cjs` 和 `babel.config.cjs`。 (9认同)