typescript - این فایل به عنوان یک ماژول ES در نظر گرفته میشود زیرا پسوند فایل آن '.js' است
من میخواهم از jtest برای انجام یک تست واحد در پروژه تایپاسکریپت (نسخه 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)
این محتویات 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;
چرا این خطا رخ داد؟ باید چه کار کنم تا تست واحد کار کند؟
پاسخ شماره ۱
شما احتمالاً "type": "module" را در فایل package.json خود دارید. اگر آن را حذف کنید، این مشکل برطرف خواهد شد.
به طور دیگر، اگر میخواهید "type": "module" خود را حفظ کنید، میتوانید jest.config.js خود را به jest.config.json تبدیل کنید (و/یا اگر یک babel.config.js دارید، آن را نیز باید به babel.config.json تبدیل کنید). توجه داشته باشید که در واقع باید آن را به فرمت JSON تبدیل کنید (پس، module.exports= را از آن حذف کنید و غیره).
این پروژه نمونه خیلی عمیقتر به همه این موارد میپردازد
پاسخ شماره ۲
امروز با این خطا برخورد کردم و میخواستم کتابخانهام را به صورت "type": "module" در package.json نگه دارم، بنابراین jest.config.js خود را به jest.config.json تغییر دادم همانطور که cmcculloh پیشنهاد میکند. مجبور شدم تغییراتی در فایل اعمال کنم تا این تغییر را پشتیبانی کند.
jest.config.js:
/* eslint-disable */
module.exports = {
displayName: '@company/admin-lib',
preset: '../../../jest.preset.js',
transform: {
'^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nx/react/plugins/jest',
'^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nx/react/babel'] }],
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../../coverage/packages/@company/admin-lib',
};معادل jest.config.json خواهد بود:
{
"displayName": "@company/admin-lib",
"preset": "../../../jest.preset.js",
"transform": {
"^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "@nx/react/plugins/jest",
"^.+\\.[tj]sx?$": ["babel-jest", { "presets": ["@nx/react/babel"] }]
},
"moduleFileExtensions": ["ts", "tsx", "js", "jsx"],
"coverageDirectory": "../../../coverage/packages/@company/admin-lib"
}
