Anonymous
Получение ошибки соответствия WebPack при поиске модуля (файла JSON) в действиях GitHub
Сообщение
Anonymous » 15 июн 2025, 11:12
У меня есть требование, когда мне нужно запустить кипарисовые тесты в соответствии с информацией о файле jublist.json . Этот файл будет создан во время выполнения, а иногда и создает проблему, поэтому я создаю по умолчанию пустой файл JSON. Я сталкиваюсь с модулем, не найденным ошибкой, когда звоню этому JSON в своем сценарии. Он работает в местном уровне без каких -либо проблем, но не выполняет действия в GitHub Deciates. Во время помощи CHATGPT я внедрил WebPack-Preprocessor , чтобы справиться с этим сценарием, но ничего не работает. Пожалуйста, кто -нибудь помогите мне пройти через этот блок.
Код: Выделить всё
const cypress = require('cypress');
const { defineConfig } = require('cypress');
const { LambdaClient, InvokeCommand } = require('@aws-sdk/client-lambda');
const { MWAAClient, CreateCliTokenCommand } = require('@aws-sdk/client-mwaa');
const {
CloudWatchLogsClient,
GetLogEventsCommand,
} = require('@aws-sdk/client-cloudwatch-logs');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const Papa = require('papaparse');
require('dotenv').config();
const { merge } = require("lodash");
const lambda = new LambdaClient({ region: 'us-west-2' });
const client = new MWAAClient({ region: 'us-west-2' });
const otplib = require('otplib');
const pdf = require("pdf-parse");
const testdataFilePath = path.resolve(__dirname, 'cypress/fixtures/testdata');
const jobFilePath = path.resolve(testdataFilePath, 'jobList.json');
const mergedPath = path.resolve(testdataFilePath, 'merged.json');
const webpack = require('@cypress/webpack-preprocessor');
const mysql = require('mysql');
const webPackConfig=require('./webpack.config.js')
function getFilePath(filename, isJobData = false) {
// Ensure merged.json always exists
if (!fs.existsSync(mergedPath)) {
fs.writeFileSync(mergedPath, JSON.stringify({}, null, 2));
}
// If specifically asking for job data path
if (isJobData) {
// Ensure jobList.json exists too
if (!fs.existsSync(jobFilePath)) {
fs.writeFileSync(jobFilePath, JSON.stringify({}, null, 2));
}
return jobFilePath;
}
// Otherwise return path for test data
return path.resolve(testdataFilePath, `testData_${filename}.json`);
}
module.exports = defineConfig({
chromeWebSecurity: false,
defaultCommandTimeout: 25000,
requestTimeout: 25000,
pageLoadTimeout: 30000,
watchForFileChanges: false,
viewportWidth: 1440,
viewportHeight: 900,
retries: 0,
reporter: 'mochawesome',
reporterOptions: {
reportDir: 'cypress/reports/',
charts: true,
video: false,
reportPageTitle: 'Test-Result',
embeddedScreenshots: true,
inlineAssets: true,
saveAllAttempts: false,
reportFilename: '[status]_[datetime]-[name]-report', // Adds the asserts inline
overwrite: true, // Prevent overwriting reports
json: true, // Generate JSON reports
},
e2e: {
grep: 'Works',
grepFilterTests: true,
specPattern: 'cypress/integration',
fixturesFolder: 'cypress/fixtures',
screenshotsFolder: 'cypress/screenshots',
videosFolder: 'cypress/videos',
downloadsFolder: 'cypress/downloads',
supportFile: 'cypress/support/e2e.js',
testIsolation: false,
retries: {
runMode: 2,
openMode: 0,
},
excludeSpecPattern: ['*/*/*/*/README.md', '*/*/*/Testing.spec.js'],
env: {
viewportWidth: 1920,
portfolio: 6,
processor: 0,
},
setupNodeEvents(on, config) {
// implement node event listeners here
require('cypress-mochawesome-reporter/plugin')(on);
const options = {
webpackOptions: webPackConfig,
watchOptions: {},
};
on('file:preprocessor', webpack({ webpackOptions: webPackConfig }));
on('after:run', (results) => {
if (!results || results.totalTests === 0) {
console.log('No tests ran, skipping report generation.');
return;
}
// ...your report generation logic here...
});
require('@cypress/grep/src/plugin')(config);
on('task',{
saveData({ key, data, filename, overwrite,jobFile=false}) {
const filePath = getFilePath(filename,jobFile);
console.log("file path in save file "+filePath);
let existing = {};
if (fs.existsSync(filePath)) {
existing = JSON.parse(fs.readFileSync(filePath));
if(existing[key] && !overwrite){
return false;
}
}
existing[key] = data;
try {
console.log("file path "+filePath);
fs.writeFileSync(filePath, JSON.stringify(existing, null, 2));
return true;
} catch (err) {
console.error("Failed to save data file:", err.message);
throw err;
}
},
})
if (!fs.existsSync(testdataFilePath)) {
fs.mkdirSync(testdataFilePath, { recursive: true });
}
if(!fs.existsSync(jobFilePath)){
fs.writeFileSync(jobFilePath,JSON.stringify({},null,2));
}
if(!fs.existsSync(mergedPath)){
fs.writeFileSync(mergedPath,JSON.stringify({},null,2));
}
return config;
},
},
});
config
Код: Выделить всё
const path = require('path');
const fs=require('fs')
const webpack = require('webpack');
const resolvedFixtures = path.resolve(process.cwd(), 'cypress/fixtures');
const fixturesDir = path.resolve(process.cwd(), 'cypress/fixtures/testdata');
const sampleFilePath = path.join(fixturesDir, 'jobList.json');
// Ensure directory exists
if (!fs.existsSync(fixturesDir)) {
fs.mkdirSync(fixturesDir, { recursive: true });
}
// Create sample file if missing
if (!fs.existsSync(sampleFilePath)) {
fs.writeFileSync(sampleFilePath, JSON.stringify({ default: true }, null, 2));
console.log(`📝 Created missing file: ${sampleFilePath}`);
}else{
console.log("fixtures folder able to find jobList.json");
}
module.exports = {
resolve: {
alias: {
'@fixtures': resolvedFixtures,
},
extensions: ['.js', '.json'],
fallback: {
fs: false,
net: false,
tls: false,
url:false,
timers: false,
crypto: require.resolve('crypto-browserify'),
stream: require.resolve('stream-browserify'),
path: require.resolve('path-browserify'),
util: require.resolve('util/'),
process: require.resolve('process/browser'),
},
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
{
test: /\.json$/,
type: 'json',
parser: {
parse: JSON.parse,
},
},
],
}
],
};
my testcase
Код: Выделить всё
let jobData = require("../../../../fixtures/testdata/jobList.json");
//const jobData = require('@fixtures/testdata/jobList.json');
const processors = jobData?.jobs?.processoor
? Object.keys(jobData.jobs.processoor)
: ['APPS', 'PAYPAL', 'OLYMPUS'];
describe('This is to start test job', { tags: ['@jobs'] }, () => {
processors.forEach((processor) => {
it(`Run sample test for for ${processor}`, () => {
//testcode
});
});
});
my github actions
Код: Выделить всё
Pre-required-file-setup:
needs: Database-Cleanup
runs-on: TEST_qa-automation
container:
image: cypress/browsers:22.12.0
options: --user root
steps:
- name: Checkout
uses: actions/checkout@v4
# Uses the official Cypress GitHub action https://github.com/cypress-io/github-action
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Pre-create jobList.json file
shell: bash
run: |
if [ ! -f "cypress/fixtures/testdata/jobList.json" ]; then
mkdir -p cypress/fixtures/testdata
echo '{}' > cypress/fixtures/testdata/jobList.json
fi
- name: Upload fixtures folder
uses: actions/upload-artifact@v4.6.0
with:
name: cypress-fixtures-files
path: cypress/fixtures
QA-On-Demand-Run:
needs: Pre-required-file-setup
runs-on: TEST_qa-automation
outputs:
cloud_url: ${{ steps.cypress-run.outputs.cloud_url }}
container:
image: cypress/browsers:22.12.0
options: --user root
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Clean and Install Dependencies
run: |
rm -rf node_modules package-lock.json
npm install --force
- name: Install jq
run: apt-get update && apt-get install -y jq
- name: Download fixtures folder
uses: actions/download-artifact@v4
with:
name: cypress-fixtures-files
path: cypress/fixtures
- name: Run Cypress Tests
id: cypress-run
continue-on-error: true
run: |
npx cypress run \
журнал ошибок
Код: Выделить всё
Oops...we found an error preparing this test file:
> cypress/integration/STAX/Engine/Jobs/payoutsJobRun.cy.js
The error was:
Error: Webpack Compilation Error
< /code>
Модуль не найден: ошибка: не может разрешить < /p>
'../../../../fixtures/testdata/jobList.json' in '/__w/test-Automation/test-Automation/cypress/integration/test/Engine/Jobs'
Я создаю Jublist File в отдельной работе и загружаю его, и мы можем загрузить файл, и все кажется в порядке, но в тесте он не может найти модуль.
Подробнее здесь:
https://stackoverflow.com/questions/796 ... -github-ac
1749975147
Anonymous
У меня есть требование, когда мне нужно запустить кипарисовые тесты в соответствии с информацией о файле jublist.json . Этот файл будет создан во время выполнения, а иногда и создает проблему, поэтому я создаю по умолчанию пустой файл JSON. Я сталкиваюсь с модулем, не найденным ошибкой, когда звоню этому JSON в своем сценарии. Он работает в местном уровне без каких -либо проблем, но не выполняет действия в GitHub Deciates. Во время помощи CHATGPT я внедрил WebPack-Preprocessor , чтобы справиться с этим сценарием, но ничего не работает. Пожалуйста, кто -нибудь помогите мне пройти через этот блок.[code]const cypress = require('cypress'); const { defineConfig } = require('cypress'); const { LambdaClient, InvokeCommand } = require('@aws-sdk/client-lambda'); const { MWAAClient, CreateCliTokenCommand } = require('@aws-sdk/client-mwaa'); const { CloudWatchLogsClient, GetLogEventsCommand, } = require('@aws-sdk/client-cloudwatch-logs'); const axios = require('axios'); const fs = require('fs'); const path = require('path'); const Papa = require('papaparse'); require('dotenv').config(); const { merge } = require("lodash"); const lambda = new LambdaClient({ region: 'us-west-2' }); const client = new MWAAClient({ region: 'us-west-2' }); const otplib = require('otplib'); const pdf = require("pdf-parse"); const testdataFilePath = path.resolve(__dirname, 'cypress/fixtures/testdata'); const jobFilePath = path.resolve(testdataFilePath, 'jobList.json'); const mergedPath = path.resolve(testdataFilePath, 'merged.json'); const webpack = require('@cypress/webpack-preprocessor'); const mysql = require('mysql'); const webPackConfig=require('./webpack.config.js') function getFilePath(filename, isJobData = false) { // Ensure merged.json always exists if (!fs.existsSync(mergedPath)) { fs.writeFileSync(mergedPath, JSON.stringify({}, null, 2)); } // If specifically asking for job data path if (isJobData) { // Ensure jobList.json exists too if (!fs.existsSync(jobFilePath)) { fs.writeFileSync(jobFilePath, JSON.stringify({}, null, 2)); } return jobFilePath; } // Otherwise return path for test data return path.resolve(testdataFilePath, `testData_${filename}.json`); } module.exports = defineConfig({ chromeWebSecurity: false, defaultCommandTimeout: 25000, requestTimeout: 25000, pageLoadTimeout: 30000, watchForFileChanges: false, viewportWidth: 1440, viewportHeight: 900, retries: 0, reporter: 'mochawesome', reporterOptions: { reportDir: 'cypress/reports/', charts: true, video: false, reportPageTitle: 'Test-Result', embeddedScreenshots: true, inlineAssets: true, saveAllAttempts: false, reportFilename: '[status]_[datetime]-[name]-report', // Adds the asserts inline overwrite: true, // Prevent overwriting reports json: true, // Generate JSON reports }, e2e: { grep: 'Works', grepFilterTests: true, specPattern: 'cypress/integration', fixturesFolder: 'cypress/fixtures', screenshotsFolder: 'cypress/screenshots', videosFolder: 'cypress/videos', downloadsFolder: 'cypress/downloads', supportFile: 'cypress/support/e2e.js', testIsolation: false, retries: { runMode: 2, openMode: 0, }, excludeSpecPattern: ['*/*/*/*/README.md', '*/*/*/Testing.spec.js'], env: { viewportWidth: 1920, portfolio: 6, processor: 0, }, setupNodeEvents(on, config) { // implement node event listeners here require('cypress-mochawesome-reporter/plugin')(on); const options = { webpackOptions: webPackConfig, watchOptions: {}, }; on('file:preprocessor', webpack({ webpackOptions: webPackConfig })); on('after:run', (results) => { if (!results || results.totalTests === 0) { console.log('No tests ran, skipping report generation.'); return; } // ...your report generation logic here... }); require('@cypress/grep/src/plugin')(config); on('task',{ saveData({ key, data, filename, overwrite,jobFile=false}) { const filePath = getFilePath(filename,jobFile); console.log("file path in save file "+filePath); let existing = {}; if (fs.existsSync(filePath)) { existing = JSON.parse(fs.readFileSync(filePath)); if(existing[key] && !overwrite){ return false; } } existing[key] = data; try { console.log("file path "+filePath); fs.writeFileSync(filePath, JSON.stringify(existing, null, 2)); return true; } catch (err) { console.error("Failed to save data file:", err.message); throw err; } }, }) if (!fs.existsSync(testdataFilePath)) { fs.mkdirSync(testdataFilePath, { recursive: true }); } if(!fs.existsSync(jobFilePath)){ fs.writeFileSync(jobFilePath,JSON.stringify({},null,2)); } if(!fs.existsSync(mergedPath)){ fs.writeFileSync(mergedPath,JSON.stringify({},null,2)); } return config; }, }, }); [/code] [b] config [/b] [code]const path = require('path'); const fs=require('fs') const webpack = require('webpack'); const resolvedFixtures = path.resolve(process.cwd(), 'cypress/fixtures'); const fixturesDir = path.resolve(process.cwd(), 'cypress/fixtures/testdata'); const sampleFilePath = path.join(fixturesDir, 'jobList.json'); // Ensure directory exists if (!fs.existsSync(fixturesDir)) { fs.mkdirSync(fixturesDir, { recursive: true }); } // Create sample file if missing if (!fs.existsSync(sampleFilePath)) { fs.writeFileSync(sampleFilePath, JSON.stringify({ default: true }, null, 2)); console.log(`📝 Created missing file: ${sampleFilePath}`); }else{ console.log("fixtures folder able to find jobList.json"); } module.exports = { resolve: { alias: { '@fixtures': resolvedFixtures, }, extensions: ['.js', '.json'], fallback: { fs: false, net: false, tls: false, url:false, timers: false, crypto: require.resolve('crypto-browserify'), stream: require.resolve('stream-browserify'), path: require.resolve('path-browserify'), util: require.resolve('util/'), process: require.resolve('process/browser'), }, }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], }, }, }, { test: /\.json$/, type: 'json', parser: { parse: JSON.parse, }, }, ], } ], }; [/code] [b] my testcase [/b] [code]let jobData = require("../../../../fixtures/testdata/jobList.json"); //const jobData = require('@fixtures/testdata/jobList.json'); const processors = jobData?.jobs?.processoor ? Object.keys(jobData.jobs.processoor) : ['APPS', 'PAYPAL', 'OLYMPUS']; describe('This is to start test job', { tags: ['@jobs'] }, () => { processors.forEach((processor) => { it(`Run sample test for for ${processor}`, () => { //testcode }); }); }); [/code] [b] my github actions [/b] [code]Pre-required-file-setup: needs: Database-Cleanup runs-on: TEST_qa-automation container: image: cypress/browsers:22.12.0 options: --user root steps: - name: Checkout uses: actions/checkout@v4 # Uses the official Cypress GitHub action https://github.com/cypress-io/github-action - name: Set up Node uses: actions/setup-node@v4 with: node-version: 20 - name: Pre-create jobList.json file shell: bash run: | if [ ! -f "cypress/fixtures/testdata/jobList.json" ]; then mkdir -p cypress/fixtures/testdata echo '{}' > cypress/fixtures/testdata/jobList.json fi - name: Upload fixtures folder uses: actions/upload-artifact@v4.6.0 with: name: cypress-fixtures-files path: cypress/fixtures QA-On-Demand-Run: needs: Pre-required-file-setup runs-on: TEST_qa-automation outputs: cloud_url: ${{ steps.cypress-run.outputs.cloud_url }} container: image: cypress/browsers:22.12.0 options: --user root steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Node uses: actions/setup-node@v4 with: node-version: 20 - name: Clean and Install Dependencies run: | rm -rf node_modules package-lock.json npm install --force - name: Install jq run: apt-get update && apt-get install -y jq - name: Download fixtures folder uses: actions/download-artifact@v4 with: name: cypress-fixtures-files path: cypress/fixtures - name: Run Cypress Tests id: cypress-run continue-on-error: true run: | npx cypress run \ [/code] [b] журнал ошибок [/b] [code]Oops...we found an error preparing this test file: > cypress/integration/STAX/Engine/Jobs/payoutsJobRun.cy.js The error was: Error: Webpack Compilation Error < /code> Модуль не найден: ошибка: не может разрешить < /p> '../../../../fixtures/testdata/jobList.json' in '/__w/test-Automation/test-Automation/cypress/integration/test/Engine/Jobs' [/code] Я создаю Jublist File в отдельной работе и загружаю его, и мы можем загрузить файл, и все кажется в порядке, но в тесте он не может найти модуль. Подробнее здесь: [url]https://stackoverflow.com/questions/79666405/getting-webpack-compliation-error-when-finding-a-module-json-file-in-github-ac[/url]