From 024ec5b1a535253dbc6450bc930109b7db8af3a5 Mon Sep 17 00:00:00 2001 From: kobenguyent Date: Tue, 20 Feb 2024 12:15:17 +0100 Subject: [PATCH 01/31] WIP --- .mocharc.js => .mocharc#.js | 4 +- bin/codecept.js | 8 +- docs/configuration.md | 2 +- examples/codecept.config.example.js | 2 +- examples/codecept.config.js | 2 +- examples/selenoid-example/codecept.conf.js | 2 +- lib/actor.js | 20 +- lib/ai.js | 13 +- lib/assert.js | 6 +- lib/assert/empty.js | 13 +- lib/assert/equal.js | 17 +- lib/assert/error.js | 4 +- lib/assert/include.js | 17 +- lib/assert/throws.js | 2 +- lib/assert/truth.js | 10 +- lib/cli.js | 22 +- lib/codecept.js | 96 +++-- lib/colorUtils.js | 6 +- lib/command/configMigrate.js | 23 +- lib/command/definitions.js | 19 +- lib/command/dryRun.js | 18 +- lib/command/generate.js | 30 +- lib/command/gherkin/init.js | 17 +- lib/command/gherkin/snippets.js | 25 +- lib/command/gherkin/steps.js | 12 +- lib/command/info.js | 15 +- lib/command/init.js | 33 +- lib/command/interactive.js | 18 +- lib/command/list.js | 16 +- lib/command/run-multiple.js | 28 +- lib/command/run-multiple/chunk.js | 10 +- lib/command/run-multiple/collection.js | 6 +- lib/command/run-multiple/run.js | 6 +- lib/command/run-rerun.js | 12 +- lib/command/run-workers.js | 13 +- lib/command/run.js | 12 +- lib/command/utils.js | 33 +- lib/command/workers/runTests.js | 8 +- lib/config.js | 15 +- lib/container.js | 26 +- lib/data/context.js | 11 +- lib/data/dataScenarioConfig.js | 2 +- lib/data/dataTableArgument.js | 2 +- lib/data/table.js | 2 +- lib/event.js | 330 +++++++++--------- lib/helper.js | 4 +- lib/helper/ApiDataFactory.js | 9 +- lib/helper/Appium.js | 21 +- lib/helper/Expect.js | 4 +- lib/helper/FileSystem.js | 32 +- lib/helper/GraphQL.js | 6 +- lib/helper/GraphQLDataFactory.js | 9 +- lib/helper/JSONResponse.js | 6 +- lib/helper/Mochawesome.js | 6 +- lib/helper/MockServer.js | 4 +- lib/helper/Nightmare.js | 33 +- lib/helper/OpenAI.js | 12 +- lib/helper/Playwright.js | 84 ++--- lib/helper/Protractor.js | 32 +- lib/helper/Puppeteer.js | 81 ++--- lib/helper/REST.js | 11 +- lib/helper/TestCafe.js | 44 +-- lib/helper/WebDriver.js | 73 ++-- lib/helper/clientscripts/PollyWebDriverExt.js | 2 +- lib/helper/errors/ConnectionRefused.js | 2 +- lib/helper/errors/ElementAssertion.js | 4 +- lib/helper/errors/ElementNotFound.js | 4 +- .../errors/RemoteBrowserConnectionRefused.js | 2 +- lib/helper/extras/Console.js | 2 +- lib/helper/extras/PlaywrightPropEngine.js | 4 +- .../extras/PlaywrightReactVueLocator.js | 2 +- lib/helper/extras/PlaywrightRestartOpts.js | 2 +- lib/helper/extras/Popup.js | 2 +- lib/helper/extras/React.js | 6 +- lib/helper/networkTraffics/utils.js | 2 +- lib/helper/scripts/blurElement.js | 2 +- lib/helper/scripts/focusElement.js | 2 +- lib/helper/scripts/highlightElement.js | 2 +- lib/helper/scripts/isElementClickable.js | 2 +- lib/helper/testcafe/testControllerHolder.js | 2 +- lib/helper/testcafe/testcafe-utils.js | 14 +- lib/history.js | 11 +- lib/hooks.js | 8 +- lib/html.js | 14 +- lib/index.js | 58 +-- lib/interfaces/bdd.js | 23 +- lib/interfaces/featureConfig.js | 2 +- lib/interfaces/gherkin.js | 26 +- lib/interfaces/scenarioConfig.js | 2 +- lib/listener/artifacts.js | 8 +- lib/listener/config.js | 15 +- lib/listener/exit.js | 6 +- lib/listener/helpers.js | 17 +- lib/listener/mocha.js | 8 +- lib/listener/retry.js | 12 +- lib/listener/steps.js | 13 +- lib/listener/timeout.js | 18 +- lib/locator.js | 13 +- lib/mochaFactory.js | 24 +- lib/output.js | 148 ++++---- lib/parser.js | 22 +- lib/pause.js | 29 +- lib/plugin/allure.js | 2 +- lib/plugin/autoDelay.js | 16 +- lib/plugin/autoLogin.js | 20 +- lib/plugin/commentStep.js | 10 +- lib/plugin/coverage.js | 21 +- lib/plugin/customLocator.js | 6 +- lib/plugin/debugErrors.js | 16 +- lib/plugin/eachElement.js | 18 +- lib/plugin/fakerTransform.js | 8 +- lib/plugin/heal.js | 24 +- lib/plugin/pauseOnFail.js | 6 +- lib/plugin/retryFailedStep.js | 13 +- lib/plugin/retryTo.js | 10 +- lib/plugin/screenshotOnFail.js | 23 +- lib/plugin/selenoid.js | 16 +- lib/plugin/standardActingHelpers.js | 2 +- lib/plugin/stepByStepReport.js | 30 +- lib/plugin/stepTimeout.js | 6 +- lib/plugin/subtitles.js | 13 +- lib/plugin/tryTo.js | 8 +- lib/plugin/wdio.js | 15 +- lib/recorder.js | 11 +- lib/rerun.js | 12 +- lib/scenario.js | 30 +- lib/secret.js | 6 +- lib/session.js | 14 +- lib/step.js | 21 +- lib/store.js | 7 +- lib/transform.js | 2 +- lib/translation.js | 6 +- lib/ui.js | 23 +- lib/utils.js | 97 ++--- lib/within.js | 16 +- lib/workerStorage.js | 4 +- lib/workers.js | 49 +-- package.json | 10 +- test/acceptance/codecept.Playwright.js | 8 +- .../acceptance/codecept.Playwright.retryTo.js | 8 +- test/acceptance/codecept.Puppeteer.js | 8 +- test/acceptance/codecept.Testcafe.js | 6 +- .../acceptance/codecept.WebDriver.devtools.js | 8 +- test/acceptance/codecept.WebDriver.js | 8 +- test/acceptance/session_test.js | 2 +- test/bdd/codecept.faker.js | 8 +- test/bdd/defs/faker.js | 2 +- test/data/I.js | 2 +- test/data/dummy_page.js | 2 +- test/data/electron/index.js | 2 +- test/data/fake_driver.js | 4 +- test/data/graphql/index.js | 14 +- test/data/graphql/models.js | 7 +- test/data/graphql/schema.js | 9 +- test/data/graphql/users_factory.js | 6 +- test/data/helper.js | 4 +- .../data/inject-fail-example/codecept.conf.js | 4 +- .../inject-fail-example/pages/arraypage.js | 2 +- .../data/inject-fail-example/pages/notpage.js | 2 +- test/data/inject-fail-example/pages/page.js | 2 +- test/data/rest/headers.js | 2 +- test/data/rest/posts_factory.js | 6 +- test/data/sandbox/bootstrap.async.js | 2 +- test/data/sandbox/bootstrapall.function.js | 2 +- test/data/sandbox/bootstrapall.object.js | 2 +- test/data/sandbox/codecept.addt.js | 4 +- ...decept.async.bootstrapall.multiple.code.js | 6 +- test/data/sandbox/codecept.bdd.js | 4 +- .../sandbox/codecept.beforetest.failure.js | 4 +- .../codecept.bootstrapall.multiple.code.js | 4 +- ...codecept.bootstrapall.multiple.function.js | 4 +- .../codecept.bootstrapall.multiple.object.js | 4 +- test/data/sandbox/codecept.customLocator.js | 4 +- test/data/sandbox/codecept.customworker.js | 4 +- test/data/sandbox/codecept.ddt.js | 4 +- test/data/sandbox/codecept.dummy.bdd.js | 4 +- test/data/sandbox/codecept.duplicate.bdd.js | 4 +- test/data/sandbox/codecept.failed.js | 4 +- test/data/sandbox/codecept.flaky.js | 4 +- test/data/sandbox/codecept.gddt.js | 4 +- test/data/sandbox/codecept.glob.js | 4 +- test/data/sandbox/codecept.grep.2.js | 4 +- test/data/sandbox/codecept.grep.js | 4 +- test/data/sandbox/codecept.js | 4 +- .../sandbox/codecept.multiple.features.js | 4 +- .../sandbox/codecept.multiple.initFailure.js | 4 +- test/data/sandbox/codecept.multiple.js | 4 +- .../codecept.non-test-events-worker.js | 4 +- .../codecept.require.multiple.several.js | 4 +- test/data/sandbox/codecept.testevents.js | 8 +- ....workers-custom-output-folder-name.conf.js | 2 +- .../sandbox/codecept.workers-glob.conf.js | 4 +- .../codecept.workers-incorrect-glob.conf.js | 4 +- test/data/sandbox/codecept.workers.conf.js | 4 +- test/data/sandbox/config.js | 4 +- .../sandbox/configs/allure/allure.conf.js | 2 +- .../allure/before_suite_test_failed.conf.js | 2 +- .../sandbox/configs/allure/codecept.po.js | 2 +- .../configs/allure/failed_ansi.conf.js | 2 +- .../configs/allure/pages/custom_steps.js | 2 +- .../sandbox/configs/allure/pages/my_page.js | 2 +- .../configs/allure/skipped_feature.conf.js | 2 +- .../configs/bootstrap/bootstrap.async.conf.js | 4 +- .../configs/bootstrap/bootstrap.conf.js | 4 +- .../configs/bootstrap/invalid_require_test.js | 2 +- test/data/sandbox/configs/bootstrap/obj.js | 4 +- test/data/sandbox/configs/bootstrap/sync.js | 4 +- .../configs/bootstrap/with.args.async.func.js | 4 +- .../bootstrap/with.args.bootstrap.teardown.js | 4 +- .../with.args.failed.bootstrap.async.func.js | 4 +- .../with.args.failed.bootstrap.teardown.js | 4 +- .../bootstrap/without.args.async.func.js | 4 +- .../without.args.bootstrap.teardown.js | 4 +- ...ithout.args.failed.bootstrap.async.func.js | 4 +- .../without.args.failed.bootstrap.teardown.js | 4 +- .../configs/codecept-invalid.config.js | 4 +- .../configs/commentStep/codecept.conf.js | 4 +- .../configs/commentStep/customHelper.js | 2 +- .../configs/definitions/codecept.inject.po.js | 4 +- .../definitions/codecept.inject.powi.js | 4 +- .../sandbox/configs/definitions/codecept.js | 4 +- .../definitions/codecept.promise.based.js | 4 +- .../configs/definitions/po/custom_steps.js | 2 +- .../configs/pageObjects/codecept.class.js | 4 +- .../configs/pageObjects/codecept.fail_po.js | 4 +- .../configs/pageObjects/codecept.inject.po.js | 4 +- .../configs/pageObjects/codecept.logs.js | 4 +- .../configs/pageObjects/codecept.po.js | 4 +- .../configs/pageObjects/customHelper.js | 4 +- .../configs/pageObjects/fs_test.fail.po.js | 4 +- .../sandbox/configs/pageObjects/fs_test.po.js | 4 +- .../pageObjects/pages/classnestedpage.js | 2 +- .../configs/pageObjects/pages/classpage.js | 2 +- .../configs/pageObjects/pages/custom_steps.js | 2 +- .../configs/pageObjects/pages/logs_page.js | 2 +- .../configs/pageObjects/pages/my_page.js | 2 +- .../configs/pageObjects/pages/second_page.js | 4 +- .../sandbox/configs/pageObjects/steps_file.js | 2 +- .../configs/retryHooks/codecept.conf.js | 4 +- .../retryHooks/codecept.retry.global.conf.js | 4 +- .../codecept.retry.global.scenario.conf.js | 4 +- .../retryHooks/codecept.retry.obj.conf.js | 4 +- .../codecept.retry.obj2.fail.conf.js | 4 +- .../data/sandbox/configs/retryHooks/helper.js | 2 +- .../run-rerun/codecept.conf.fail_test.js | 4 +- .../configs/run-rerun/codecept.conf.js | 4 +- .../run-rerun/codecept.conf.min_less_max.js | 4 +- .../run-rerun/codecept.conf.min_more_max.js | 4 +- .../sandbox/configs/run-rerun/customHelper.js | 2 +- .../sandbox/configs/skip/codecept.conf.js | 4 +- test/data/sandbox/configs/skip/skip_test.js | 2 +- .../step_timeout/codecept-1000.conf.js | 4 +- .../step_timeout/codecept-2000.conf.js | 4 +- .../configs/step_timeout/customHelper.js | 2 +- .../configs/testArtifacts/codecept.conf.js | 4 +- .../configs/testArtifacts/customHelper.js | 2 +- .../configs/testArtifacts/first_test.js | 2 +- .../sandbox/configs/timeouts/codecept.conf.js | 4 +- .../configs/timeouts/codecept.timeout.conf.js | 4 +- .../timeouts/codecept.timeout.obj.conf.js | 4 +- .../sandbox/configs/timeouts/customHelper.js | 2 +- .../sandbox/configs/todo/codecept.conf.js | 4 +- test/data/sandbox/configs/todo/first_test.js | 2 +- .../configs/translation/codecept.conf.js | 4 +- .../workers/codecept.workers-negative.conf.js | 4 +- .../custom-worker/share_test.worker.js | 2 +- test/data/sandbox/custom_worker_helper.js | 6 +- test/data/sandbox/eventHandlers.js | 2 +- .../step_definitions/my_other_steps.js | 2 +- test/data/sandbox/flaky_test.flaky.js | 2 +- test/data/sandbox/flaky_test.retry.js | 2 +- test/data/sandbox/flaky_test.retryFailed.js | 2 +- test/data/sandbox/hooks.js | 2 +- test/data/sandbox/i18n/codecept.bdd.de.js | 4 +- .../non_test_event.worker.js | 2 +- test/data/sandbox/retry_helper.js | 4 +- test/data/sandbox/session_helper.js | 4 +- test/data/sandbox/support/bdd_helper.js | 6 +- test/data/sandbox/support/custom_steps.js | 2 +- test/data/sandbox/support/failureHelper.js | 2 +- test/data/sandbox/support/my_page.js | 2 +- test/data/sandbox/support/second_page.js | 2 +- test/data/sandbox/teardownall.function.js | 2 +- test/data/sandbox/teardownall.object.js | 2 +- test/data/sandbox/test_before_failure.js | 2 +- test/data/sandbox/within_helper.js | 8 +- .../sandbox/workers/retry_test.workers.js | 2 +- test/data/sandbox/workers_helper.js | 9 +- test/graphql/GraphQLDataFactory_test.js | 12 +- test/graphql/GraphQL_test.js | 11 +- test/helper/AppiumV2Web_test.js | 2 +- test/helper/AppiumV2_ios_test.js | 11 +- test/helper/AppiumV2_test.js | 16 +- test/helper/AppiumWeb_test.js | 2 +- test/helper/Appium_test.js | 16 +- test/helper/Expect_test.js | 9 +- test/helper/JSONResponse_test.js | 11 +- test/helper/MockServer_test.js | 13 +- test/helper/Playwright_test.js | 25 +- test/helper/Puppeteer_test.js | 23 +- test/helper/TestCafe_test.js | 15 +- .../helper/WebDriver.noSeleniumServer_test.js | 22 +- test/helper/WebDriver_devtools_test.js | 24 +- test/helper/WebDriver_test.js | 24 +- test/helper/webapi.js | 16 +- test/plugin/plugin_test.js | 6 +- test/rest/ApiDataFactory_test.js | 10 +- test/rest/REST_test.js | 15 +- test/runner/bdd_test.js | 6 +- test/runner/before_failure_test.js | 4 +- test/runner/bootstrap_test.js | 6 +- test/runner/codecept_test.js | 13 +- test/runner/comment_step_test.js | 6 +- test/runner/consts.js | 4 +- test/runner/definitions_test.js | 11 +- test/runner/dry_run_test.js | 8 +- test/runner/init_test.js | 10 +- test/runner/interface_test.js | 6 +- test/runner/list_test.js | 6 +- test/runner/pageobject_test.js | 6 +- test/runner/retry_hooks_test.js | 6 +- test/runner/run_multiple_test.js | 8 +- test/runner/run_rerun_test.js | 10 +- test/runner/run_workers_test.js | 8 +- test/runner/session_test.js | 5 +- test/runner/skip_test.js | 6 +- test/runner/step_timeout_test.js | 6 +- test/runner/timeout_test.js | 6 +- test/runner/todo_test.js | 6 +- test/runner/translation_test.js | 8 +- test/runner/within_test.js | 5 +- test/support/ScreenshotSessionHelper.js | 6 +- test/support/TestHelper.js | 2 +- test/unit/actor_test.js | 18 +- test/unit/ai_test.js | 9 +- test/unit/assert/empty_test.js | 10 +- test/unit/assert/equal_test.js | 9 +- test/unit/assert/include_test.js | 9 +- test/unit/assert_test.js | 9 +- test/unit/bdd_test.js | 32 +- test/unit/config_test.js | 7 +- test/unit/container_test.js | 27 +- test/unit/data/dataTableArgument_test.js | 9 +- test/unit/data/table_test.js | 7 +- test/unit/data/ui_test.js | 18 +- test/unit/helper/FileSystem_test.js | 16 +- test/unit/helper/element_not_found_test.js | 7 +- test/unit/html_test.js | 42 +-- test/unit/locator_test.js | 12 +- test/unit/output_test.js | 18 +- test/unit/parser_test.js | 7 +- test/unit/plugin/customLocator_test.js | 9 +- test/unit/plugin/eachElement_test.js | 16 +- test/unit/plugin/retryFailedStep_test.js | 23 +- test/unit/plugin/retryto_test.js | 11 +- test/unit/plugin/screenshotOnFail_test.js | 16 +- test/unit/plugin/subtitles_test.js | 12 +- test/unit/plugin/tryTo_test.js | 11 +- test/unit/recorder_test.js | 7 +- test/unit/scenario_test.js | 38 +- test/unit/secret_test.js | 4 +- test/unit/steps_test.js | 18 +- test/unit/ui_test.js | 15 +- test/unit/utils_test.js | 17 +- test/unit/worker_test.js | 13 +- translations/de-DE.js | 2 +- translations/fr-FR.js | 2 +- translations/it-IT.js | 2 +- translations/ja-JP.js | 2 +- translations/pl-PL.js | 2 +- translations/pt-BR.js | 2 +- translations/ru-RU.js | 2 +- translations/zh-CN.js | 2 +- translations/zh-TW.js | 2 +- typings/index.d.ts | 2 +- 375 files changed, 2009 insertions(+), 2084 deletions(-) rename .mocharc.js => .mocharc#.js (65%) diff --git a/.mocharc.js b/.mocharc#.js similarity index 65% rename from .mocharc.js rename to .mocharc#.js index 03529fe60..23bc63079 100644 --- a/.mocharc.js +++ b/.mocharc#.js @@ -1,3 +1,3 @@ -module.exports = { +export default { "require": "./test/support/setup.js" -} +}; diff --git a/bin/codecept.js b/bin/codecept.js index 9d8ddfc3c..bbf72d514 100755 --- a/bin/codecept.js +++ b/bin/codecept.js @@ -1,8 +1,8 @@ #!/usr/bin/env node -const program = require('commander'); -const Codecept = require('../lib/codecept'); -const { print, error } = require('../lib/output'); -const { printError } = require('../lib/command/utils'); +import program from 'commander'; +import Codecept from '../lib/codecept'; +import { print, error } from '../lib/output.js'; +import { printError } from '../lib/command/utils.js'; const errorHandler = (fn) => async (...args) => { try { diff --git a/docs/configuration.md b/docs/configuration.md index 2d07bd58a..1eb7687d2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -21,7 +21,7 @@ After running `codeceptjs init` it should be saved in test root. | `include?` | `any` | Include page objects to access them via dependency injection ```I: "./custom_steps.js", loginPage: "./pages/Login.js", User: "./pages/User.js", ``` Configured modules can be injected by name in a Scenario: ```Scenario('test', { I, loginPage, User }) ``` | | `mocha?` | `any` | [Mocha test runner options](https://mochajs.org/#configuring-mocha-nodejs), additional [reporters](https://codecept.io/reports/#xml) can be configured here. Example: ```mocha: { "mocha-junit-reporter": { stdout: "./output/console.log", options: { mochaFile: "./output/result.xml", attachments: true //add screenshot for a failed test } } } ``` | | `noGlobals?` | `boolean` | Disable registering global functions (Before, Scenario, etc). Not recommended | -| `output` | `string` | Where to store failure screenshots, artifacts, etc ```output: './output' ``` | +| `output` | `string` | Where to store failure screenshots, artifacts, etc ```output: './output.js' ``` | | `plugins?` | `any` | Enable CodeceptJS plugins. Example: ```plugins: { autoDelay: { enabled: true } } ``` | | `require?` | `string`[] | [Require additional JS modules](https://codecept.io/configuration/#require) Example: ``` require: ["should"] ``` | | `teardown?` | (() => `Promise`<`void`\>) \| `boolean` \| `string` | [Execute code after tests](https://codecept.io/bootstrap/) finished. Can be either JS module file or async function: ```teardown: async () => server.stop(), ``` or ```teardown: 'teardown.js', ``` | diff --git a/examples/codecept.config.example.js b/examples/codecept.config.example.js index bd61e26a0..77f4d941b 100644 --- a/examples/codecept.config.example.js +++ b/examples/codecept.config.example.js @@ -5,7 +5,7 @@ console.log(process.env.profile); exports.config = { tests: './*_test.js', timeout: 10000, - output: './output', + output: './output.js', helpers: { WebDriver: { url: 'http://localhost', diff --git a/examples/codecept.config.js b/examples/codecept.config.js index 2af92dd88..c4167f9ab 100644 --- a/examples/codecept.config.js +++ b/examples/codecept.config.js @@ -1,5 +1,5 @@ exports.config = { - output: './output', + output: './output.js', helpers: { Playwright: { url: 'http://github.com', diff --git a/examples/selenoid-example/codecept.conf.js b/examples/selenoid-example/codecept.conf.js index 59666c7e1..0becfe72f 100644 --- a/examples/selenoid-example/codecept.conf.js +++ b/examples/selenoid-example/codecept.conf.js @@ -1,6 +1,6 @@ exports.config = { tests: './*_test.js', - output: './output', + output: './output.js', helpers: { WebDriver: { url: 'http://localhost', diff --git a/lib/actor.js b/lib/actor.js index a53a03fe4..4712e5155 100644 --- a/lib/actor.js +++ b/lib/actor.js @@ -1,11 +1,11 @@ -const Step = require('./step'); -const { MetaStep } = require('./step'); -const container = require('./container'); -const { methodsOfObject } = require('./utils'); -const recorder = require('./recorder'); -const event = require('./event'); -const store = require('./store'); -const output = require('./output'); +import Step from './step.js'; +import { MetaStep } from './step.js'; +import container from './container.js'; +import { methodsOfObject } from './utils.js'; +import recorder from './recorder.js'; +import * as event from './event.js'; +import { store } from './store.js'; +import output from './output.js'; /** * @interface @@ -69,7 +69,7 @@ class Actor { * Wraps helper methods into promises. * @ignore */ -module.exports = function (obj = {}) { +export default function (obj = {}) { if (!store.actor) { store.actor = new Actor(); } @@ -117,7 +117,7 @@ module.exports = function (obj = {}) { }); return actor; -}; +} function recordStep(step, args) { step.status = 'queued'; diff --git a/lib/ai.js b/lib/ai.js index e1e90575e..6f1c2e588 100644 --- a/lib/ai.js +++ b/lib/ai.js @@ -1,8 +1,9 @@ -const { Configuration, OpenAIApi } = require('openai'); -const debug = require('debug')('codeceptjs:ai'); -const config = require('./config'); -const output = require('./output'); -const { removeNonInteractiveElements, minifyHtml, splitByChunks } = require('./html'); +import { Configuration, OpenAIApi } from 'openai'; +import debug from 'debug'; +debug('codeceptjs:ai'); +import config from './config.js'; +import output from './output.js'; +import { removeNonInteractiveElements, minifyHtml, splitByChunks } from './html.js'; const defaultConfig = { model: 'gpt-3.5-turbo-16k', @@ -177,4 +178,4 @@ function parseCodeBlocks(response) { return modifiedSnippets.filter(snippet => !!snippet); } -module.exports = AiAssistant; +export default AiAssistant; diff --git a/lib/assert.js b/lib/assert.js index 7e2cbc46d..08cbe7d63 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -1,4 +1,4 @@ -const AssertionFailedError = require('./assert/error'); +import AssertionFailedError from './assert/error.js'; /** * Abstract assertion class introduced for more verbose and customizable messages. @@ -20,7 +20,7 @@ const AssertionFailedError = require('./assert/error'); * to get more customizable exception messages. * */ -class Assertion { +export default class Assertion { constructor(comparator, params) { this.comparator = comparator; this.params = params || {}; @@ -68,5 +68,3 @@ class Assertion { return this.getException(); } } - -module.exports = Assertion; diff --git a/lib/assert/empty.js b/lib/assert/empty.js index 2b1fd67fe..798df0171 100644 --- a/lib/assert/empty.js +++ b/lib/assert/empty.js @@ -1,7 +1,7 @@ -const Assertion = require('../assert'); -const AssertionFailedError = require('./error'); -const { template } = require('../utils'); -const output = require('../output'); +import Assertion from '../assert.js'; +import AssertionFailedError from './error.js'; +import { template } from '../utils.js'; +import output from '../output.js'; class EmptinessAssertion extends Assertion { constructor(params) { @@ -37,7 +37,8 @@ class EmptinessAssertion extends Assertion { } } -module.exports = { - Assertion: EmptinessAssertion, +export { EmptinessAssertion as Assertion }; + +export default { empty: subject => new EmptinessAssertion({ subject }), }; diff --git a/lib/assert/equal.js b/lib/assert/equal.js index 17db64e5c..22f39f7aa 100644 --- a/lib/assert/equal.js +++ b/lib/assert/equal.js @@ -1,7 +1,7 @@ -const Assertion = require('../assert'); -const AssertionFailedError = require('./error'); -const { template } = require('../utils'); -const output = require('../output'); +import Assertion from '../assert.js'; +import AssertionFailedError from './error.js'; +import { template } from '../utils.js'; +import output from '../output.js'; class EqualityAssertion extends Assertion { constructor(params) { @@ -38,8 +38,12 @@ class EqualityAssertion extends Assertion { } } -module.exports = { - Assertion: EqualityAssertion, +export function fileEquals(file) { + return new EqualityAssertion({ file, jar: 'contents of {{file}}' }); +} + +export { EqualityAssertion as Assertion }; +export default { equals: jar => new EqualityAssertion({ jar }), urlEquals: (baseUrl) => { const assert = new EqualityAssertion({ jar: 'url of current page' }); @@ -51,5 +55,4 @@ module.exports = { }; return assert; }, - fileEquals: file => new EqualityAssertion({ file, jar: 'contents of {{file}}' }), }; diff --git a/lib/assert/error.js b/lib/assert/error.js index 072d82372..4803e1b1c 100644 --- a/lib/assert/error.js +++ b/lib/assert/error.js @@ -1,4 +1,4 @@ -const subs = require('../utils').template; +import { template as subs } from '../utils.js'; /** * Assertion errors, can provide a detailed error messages. @@ -29,4 +29,4 @@ function AssertionFailedError(params, template) { AssertionFailedError.prototype = Object.create(Error.prototype); AssertionFailedError.constructor = AssertionFailedError; -module.exports = AssertionFailedError; +export default AssertionFailedError; diff --git a/lib/assert/include.js b/lib/assert/include.js index 6019bcc59..1466f23fb 100644 --- a/lib/assert/include.js +++ b/lib/assert/include.js @@ -1,7 +1,7 @@ -const Assertion = require('../assert'); -const AssertionFailedError = require('./error'); -const { template } = require('../utils'); -const output = require('../output'); +import Assertion from '../assert.js'; +import AssertionFailedError from './error.js'; +import { template } from '../utils.js'; +import output from '../output.js'; const MAX_LINES = 10; @@ -64,15 +64,18 @@ class InclusionAssertion extends Assertion { } } -module.exports = { - Assertion: InclusionAssertion, +export { InclusionAssertion as Assertion }; +export default { includes: (needleType) => { needleType = needleType || 'string'; return new InclusionAssertion({ jar: needleType }); }, - fileIncludes: file => new InclusionAssertion({ file, jar: 'file {{file}}' }), }; function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); } + +export function fileIncludes(file) { + return new InclusionAssertion({ file, jar: 'file {{file}}' }); +} diff --git a/lib/assert/throws.js b/lib/assert/throws.js index c5b97f007..731c7f075 100644 --- a/lib/assert/throws.js +++ b/lib/assert/throws.js @@ -17,4 +17,4 @@ function errorThrown(actual, expected) { return null; } -module.exports = errorThrown; +export default errorThrown; diff --git a/lib/assert/truth.js b/lib/assert/truth.js index 0d72ba491..01c485c15 100644 --- a/lib/assert/truth.js +++ b/lib/assert/truth.js @@ -1,7 +1,7 @@ -const Assertion = require('../assert'); -const AssertionFailedError = require('./error'); -const { template } = require('../utils'); -const output = require('../output'); +import Assertion from '../assert.js'; +import AssertionFailedError from './error.js'; +import { template } from '../utils.js'; +import output from '../output.js'; class TruthAssertion extends Assertion { constructor(params) { @@ -31,7 +31,7 @@ class TruthAssertion extends Assertion { } } -module.exports = { +export default { Assertion: TruthAssertion, truth: (subject, type) => new TruthAssertion({ subject, type }), }; diff --git a/lib/cli.js b/lib/cli.js index 832f755db..391a300b0 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -1,9 +1,13 @@ -const { reporters: { Base } } = require('mocha'); -const ms = require('ms'); -const event = require('./event'); -const AssertionFailedError = require('./assert/error'); -const output = require('./output'); -const { MetaStep } = require('./step'); +import mocha from 'mocha'; + +import ms from "ms"; + +import * as event from "./event.js"; + +import output from "./output.js"; +import AssertionFailedError from "./assert/error.js"; + +const { reporters: { Base } } = mocha; const cursor = Base.cursor; let currentMetaStep = []; @@ -25,7 +29,7 @@ class Cli extends Base { const showSteps = level >= 1; if (level >= 2) { - const Containter = require('./container'); + const Containter = require('./container.js'); output.print(output.styles.debug(`Helpers: ${Object.keys(Containter.helpers()).join(', ')}`)); output.print(output.styles.debug(`Plugins: ${Object.keys(Containter.plugins()).join(', ')}`)); } @@ -240,6 +244,6 @@ function skipTestConfig(test, message) { test.state = 'skipped'; } -module.exports = function (runner, opts) { +export default function cli(runner, opts) { return new Cli(runner, opts); -}; +} diff --git a/lib/codecept.js b/lib/codecept.js index fe749fd6e..bcadfec94 100644 --- a/lib/codecept.js +++ b/lib/codecept.js @@ -1,19 +1,54 @@ -const { existsSync, readFileSync } = require('fs'); -const glob = require('glob'); -const fsPath = require('path'); -const { resolve } = require('path'); - -const container = require('./container'); -const Config = require('./config'); -const event = require('./event'); -const runHook = require('./hooks'); -const output = require('./output'); -const { emptyFolder } = require('./utils'); +import { existsSync, readFileSync } from 'fs'; +import glob from 'glob'; +import fsPath from 'path'; +import { resolve } from 'path'; +import container from './container.js'; +import Config from './config.js'; +import * as event from './event.js'; +import runHook from './hooks.js'; +import output from './output.js'; +import { emptyFolder } from './utils.js'; +import path from "path"; +import generated from "@codeceptjs/helper"; +import * as index from './index.js'; + +import actor0 from "./actor.js"; + +import pause0 from "./pause.js"; + +import within0 from "./within.js"; + +import session0 from "./session.js"; + +import data from "./data/table.js"; + +import build from "./locator.js"; + +import secret from './secret.js'; + +// BDD +import stepDefinitions from "./interfaces/bdd.js"; + +import listener from "./listener/steps.js"; + +import listener0 from "./listener/artifacts.js"; + +import listener01 from "./listener/config.js"; + +import listener012 from "./listener/helpers.js"; + +import listener0123 from "./listener/retry.js"; + +import listener01234 from "./listener/timeout.js"; + +import listener012345 from "./listener/exit.js"; + +const __dirname = path.resolve(); /** * CodeceptJS runner */ -class Codecept { +export default class Codecept { /** * Create CodeceptJS runner. * Config and options should be passed @@ -70,21 +105,18 @@ class Codecept { if (this.config.emptyOutputFolder) emptyFolder(global.output_dir); if (!this.config.noGlobals) { - global.Helper = global.codecept_helper = require('@codeceptjs/helper'); - global.actor = global.codecept_actor = require('./actor'); - global.pause = require('./pause'); - global.within = require('./within'); - global.session = require('./session'); - global.DataTable = require('./data/table'); - global.locate = locator => require('./locator').build(locator); + global.Helper = global.codecept_helper = generated; + global.actor = global.codecept_actor = actor0; + global.pause = pause0; + global.within = within0; + global.session = session0; + global.DataTable = data; + global.locate = locator => new build(locator); global.inject = container.support; global.share = container.share; - global.secret = require('./secret').secret; + global.secret = secret; global.codecept_debug = output.debug; - global.codeceptjs = require('./index'); // load all objects - - // BDD - const stepDefinitions = require('./interfaces/bdd'); + global.codeceptjs = index; // load all objects global.Given = stepDefinitions.Given; global.When = stepDefinitions.When; global.Then = stepDefinitions.Then; @@ -100,13 +132,13 @@ class Codecept { */ runHooks() { // default hooks - runHook(require('./listener/steps')); - runHook(require('./listener/artifacts')); - runHook(require('./listener/config')); - runHook(require('./listener/helpers')); - runHook(require('./listener/retry')); - runHook(require('./listener/timeout')); - runHook(require('./listener/exit')); + runHook(listener); + runHook(listener0); + runHook(listener01); + runHook(listener012); + runHook(listener0123); + runHook(listener01234); + runHook(listener012345); // custom hooks (previous iteration of plugins) this.config.hooks.forEach(hook => runHook(hook)); @@ -211,5 +243,3 @@ class Codecept { return JSON.parse(readFileSync(`${__dirname}/../package.json`, 'utf8')).version; } } - -module.exports = Codecept; diff --git a/lib/colorUtils.js b/lib/colorUtils.js index ce1f6465a..c344d9df5 100644 --- a/lib/colorUtils.js +++ b/lib/colorUtils.js @@ -189,7 +189,7 @@ function convertHexColorToRgba(hex) { * * @param {string} color Color as a string, i.e. rgb(85,0,0) */ -function convertColorToRGBA(color) { +export function convertColorToRGBA(color) { const cstr = `${color}`.toLowerCase().trim() || ''; if (!/^rgba?\(.+?\)$/.test(cstr)) { @@ -221,7 +221,7 @@ function convertColorToRGBA(color) { * * @param {string} prop CSS Property name */ -function isColorProperty(prop) { +export function isColorProperty(prop) { return [ 'color', 'background', @@ -248,7 +248,7 @@ function isColorProperty(prop) { ].indexOf(prop) > -1; } -module.exports = { +export default { isColorProperty, convertColorToRGBA, convertColorNameToHex, diff --git a/lib/command/configMigrate.js b/lib/command/configMigrate.js index b06815359..c01e3584a 100644 --- a/lib/command/configMigrate.js +++ b/lib/command/configMigrate.js @@ -1,15 +1,14 @@ -const colors = require('chalk'); -const fs = require('fs'); -const inquirer = require('inquirer'); -const mkdirp = require('mkdirp'); -const path = require('path'); -const util = require('util'); +import colors from 'chalk'; +import fs from 'fs'; +import inquirer from 'inquirer'; +import mkdirp from 'mkdirp'; +import path from 'path'; +import util from 'util'; +import { print, success, error } from '../output.js'; +import { fileExists } from '../utils.js'; +import { getTestRoot } from './utils.js'; -const { print, success, error } = require('../output'); -const { fileExists } = require('../utils'); -const { getTestRoot } = require('./utils'); - -module.exports = function (initPath) { +export default function (initPath) { const testsPath = getTestRoot(initPath); print(); @@ -68,4 +67,4 @@ module.exports = function (initPath) { finish(); } }); -}; +} diff --git a/lib/command/definitions.js b/lib/command/definitions.js index 3751fe5fa..23469884c 100644 --- a/lib/command/definitions.js +++ b/lib/command/definitions.js @@ -1,11 +1,10 @@ -const fs = require('fs'); -const path = require('path'); - -const { getConfig, getTestRoot } = require('./utils'); -const Codecept = require('../codecept'); -const container = require('../container'); -const output = require('../output'); -const actingHelpers = [...require('../plugin/standardActingHelpers'), 'REST']; +import fs from 'fs'; +import path from 'path'; +import { getConfig, getTestRoot } from './utils.js'; +import Codecept from '../codecept'; +import container from '../container.js'; +import output from '../output.js'; +const actingHelpers = [...require('../plugin/standardActingHelpers.js'), 'REST']; /** * Prepare data and generate content of definitions file @@ -104,7 +103,7 @@ const helperNames = []; /** @type {Array} */ const customHelpers = []; -module.exports = function (genPath, options) { +export default function (genPath, options) { const configFile = options.config || genPath; /** @type {string} */ const testsPath = getTestRoot(configFile); @@ -206,7 +205,7 @@ module.exports = function (genPath, options) { fs.writeFileSync(path.join(targetFolderPath, 'steps.d.ts'), definitionsFileContent); output.print('TypeScript Definitions provide autocompletion in Visual Studio Code and other IDEs'); output.print('Definitions were generated in steps.d.ts'); -}; +} /** * Returns the relative path from the to the targeted folder. diff --git a/lib/command/dryRun.js b/lib/command/dryRun.js index 426d20e07..970a1f213 100644 --- a/lib/command/dryRun.js +++ b/lib/command/dryRun.js @@ -1,12 +1,12 @@ -const { getConfig, getTestRoot } = require('./utils'); -const Config = require('../config'); -const Codecept = require('../codecept'); -const output = require('../output'); -const event = require('../event'); -const store = require('../store'); -const Container = require('../container'); +import { getConfig, getTestRoot } from './utils.js'; +import Config from '../config.js'; +import Codecept from '../codecept'; +import output from '../output.js'; +import * as event from '../event.js'; +import { store } from '../store.js'; +import Container from '../container.js'; -module.exports = async function (test, options) { +export default async function (test, options) { if (options.grep) process.env.grep = options.grep.toLowerCase(); const configFile = options.config; let codecept; @@ -44,7 +44,7 @@ module.exports = async function (test, options) { console.error(err); process.exit(1); } -}; +} function printTests(files) { const figures = require('figures'); diff --git a/lib/command/generate.js b/lib/command/generate.js index cc9e558e4..02362e658 100644 --- a/lib/command/generate.js +++ b/lib/command/generate.js @@ -1,16 +1,12 @@ -const colors = require('chalk'); -const fs = require('fs'); -const inquirer = require('inquirer'); -const mkdirp = require('mkdirp'); -const path = require('path'); -const { - fileExists, ucfirst, lcfirst, beautify, -} = require('../utils'); -const output = require('../output'); -const generateDefinitions = require('./definitions'); -const { - getConfig, getTestRoot, safeFileWrite, readConfig, -} = require('./utils'); +import colors from 'chalk'; +import fs from 'fs'; +import inquirer from 'inquirer'; +import mkdirp from 'mkdirp'; +import path from 'path'; +import { fileExists, ucfirst, lcfirst, beautify } from '../utils.js'; +import output from '../output.js'; +import generateDefinitions from './definitions'; +import { getConfig, getTestRoot, safeFileWrite, readConfig } from './utils.js'; let extension = 'js'; @@ -22,7 +18,7 @@ Scenario('test something', async ({ {{actor}} }) => { `; // generates empty test -module.exports.test = function (genPath) { +export const test = function (genPath) { const testsPath = getTestRoot(genPath); global.codecept_dir = testsPath; const config = getConfig(testsPath); @@ -57,7 +53,7 @@ module.exports.test = function (genPath) { if (!fileExists(dir)) mkdirp.sync(dir); let testContent = testTemplate.replace('{{feature}}', result.feature); - const container = require('../container'); + const container = require('../container.js'); container.create(config, {}); // translate scenario test if (container.translation().loaded) { @@ -107,7 +103,7 @@ module.exports = new {{name}}(); export = {{name}}; `; -module.exports.pageObject = function (genPath, opts) { +export const pageObject = function (genPath, opts) { const testsPath = getTestRoot(genPath); const config = getConfig(testsPath); const kind = opts.T || 'page'; @@ -224,7 +220,7 @@ class {{name}} extends Helper { module.exports = {{name}}; `; -module.exports.helper = function (genPath) { +export const helper = function (genPath) { const testsPath = getTestRoot(genPath); output.print('Creating a new helper'); diff --git a/lib/command/gherkin/init.js b/lib/command/gherkin/init.js index b0aabe4a8..4ccf5cd65 100644 --- a/lib/command/gherkin/init.js +++ b/lib/command/gherkin/init.js @@ -1,11 +1,8 @@ -const path = require('path'); -const mkdirp = require('mkdirp'); - -const output = require('../../output'); -const { fileExists } = require('../../utils'); -const { - getConfig, getTestRoot, updateConfig, safeFileWrite, -} = require('../utils'); +import path from 'path'; +import mkdirp from 'mkdirp'; +import output from '../../output.js'; +import { fileExists } from '../../utils.js'; +import { getConfig, getTestRoot, updateConfig, safeFileWrite } from '../utils.js'; const featureFile = `Feature: Business rules In order to achieve my goals @@ -24,7 +21,7 @@ Given('I have a defined step', () => { }); `; -module.exports = function (genPath) { +export default function (genPath) { const testsPath = getTestRoot(genPath); const config = getConfig(testsPath); @@ -68,4 +65,4 @@ module.exports = function (genPath) { output.success('Gherkin setup is done.'); output.success('Start writing feature files and implement corresponding steps.'); -}; +} diff --git a/lib/command/gherkin/snippets.js b/lib/command/gherkin/snippets.js index e0f92e11a..d98785122 100644 --- a/lib/command/gherkin/snippets.js +++ b/lib/command/gherkin/snippets.js @@ -1,14 +1,13 @@ -const escapeStringRegexp = require('escape-string-regexp'); -const fs = require('fs'); -const Gherkin = require('@cucumber/gherkin'); -const Messages = require('@cucumber/messages'); -const glob = require('glob'); -const fsPath = require('path'); - -const { getConfig, getTestRoot } = require('../utils'); -const Codecept = require('../../codecept'); -const output = require('../../output'); -const { matchStep } = require('../../interfaces/bdd'); +import escapeStringRegexp from 'escape-string-regexp'; +import fs from 'fs'; +import Gherkin from '@cucumber/gherkin'; +import * as Messages from '@cucumber/messages'; +import glob from 'glob'; +import fsPath from 'path'; +import { getConfig, getTestRoot } from '../utils.js'; +import Codecept from '../../codecept'; +import output from '../../output.js'; +import { matchStep } from '../../interfaces/bdd.js'; const uuidFn = Messages.IdGenerator.uuid(); const builder = new Gherkin.AstBuilder(uuidFn); @@ -16,7 +15,7 @@ const matcher = new Gherkin.GherkinClassicTokenMatcher(); const parser = new Gherkin.Parser(builder, matcher); parser.stopAtFirstError = false; -module.exports = function (genPath, options) { +export default function (genPath, options) { const configFile = options.config || genPath; const testsPath = getTestRoot(configFile); const config = getConfig(configFile); @@ -129,4 +128,4 @@ ${step.type}(${step.regexp ? '/^' : "'"}${step}${step.regexp ? '$/' : "'"}, () = output.success(`Snippets added to ${output.colors.bold(stepFile)}`); fs.writeFileSync(stepFile, fs.readFileSync(stepFile).toString() + snippets.join('\n') + '\n'); // eslint-disable-line } -}; +} diff --git a/lib/command/gherkin/steps.js b/lib/command/gherkin/steps.js index ee149eb5b..6e2a68cd7 100644 --- a/lib/command/gherkin/steps.js +++ b/lib/command/gherkin/steps.js @@ -1,9 +1,9 @@ -const { getConfig, getTestRoot } = require('../utils'); -const Codecept = require('../../codecept'); -const output = require('../../output'); -const { getSteps } = require('../../interfaces/bdd'); +import { getConfig, getTestRoot } from '../utils.js'; +import Codecept from '../../codecept'; +import output from '../../output.js'; +import { getSteps } from '../../interfaces/bdd.js'; -module.exports = function (genPath, options) { +export default function (genPath, options) { const configFile = options.config || genPath; const testsPath = getTestRoot(configFile); const config = getConfig(configFile); @@ -22,4 +22,4 @@ module.exports = function (genPath, options) { if (!Object.keys(steps).length) { output.error('No Gherkin steps defined'); } -}; +} diff --git a/lib/command/info.js b/lib/command/info.js index 933a469a6..94d15d9c5 100644 --- a/lib/command/info.js +++ b/lib/command/info.js @@ -1,10 +1,9 @@ -const envinfo = require('envinfo'); +import envinfo from 'envinfo'; +import { getConfig, getTestRoot } from './utils.js'; +import Codecept from '../codecept'; +import output from '../output.js'; -const { getConfig, getTestRoot } = require('./utils'); -const Codecept = require('../codecept'); -const output = require('../output'); - -module.exports = async function (path) { +export default async function (path) { const testsPath = getTestRoot(path); const config = getConfig(testsPath); const codecept = new Codecept(config, {}); @@ -36,9 +35,9 @@ module.exports = async function (path) { output.print('Or ask them on our discussion board: https://codecept.discourse.group/'); output.print('Please copy environment info when you report issues on GitHub: https://github.com/Codeception/CodeceptJS/issues'); output.print('***************************************'); -}; +} -module.exports.getMachineInfo = async () => { +export const getMachineInfo = async () => { const info = { nodeInfo: await envinfo.helpers.getNodeInfo(), osInfo: await envinfo.helpers.getOSInfo(), diff --git a/lib/command/init.js b/lib/command/init.js index 0e1321646..976710f7a 100644 --- a/lib/command/init.js +++ b/lib/command/init.js @@ -1,17 +1,16 @@ -const colors = require('chalk'); -const fs = require('fs'); -const inquirer = require('inquirer'); -const mkdirp = require('mkdirp'); -const path = require('path'); -const { inspect } = require('util'); -const spawn = require('cross-spawn'); - -const { print, success, error } = require('../output'); -const { fileExists, beautify, installedLocally } = require('../utils'); -const { getTestRoot } = require('./utils'); -const generateDefinitions = require('./definitions'); -const { test: generateTest } = require('./generate'); -const isLocal = require('../utils').installedLocally(); +import colors from 'chalk'; +import fs from 'fs'; +import inquirer from 'inquirer'; +import mkdirp from 'mkdirp'; +import path from 'path'; +import { inspect } from 'util'; +import spawn from 'cross-spawn'; +import { print, success, error } from '../output.js'; +import { fileExists, beautify, installedLocally } from '../utils.js'; +import { getTestRoot } from './utils.js'; +import generateDefinitions from './definitions'; +import { test as generateTest } from './generate'; +const isLocal = require('../utils.js').installedLocally(); const defaultConfig = { tests: './*_test.js', @@ -67,7 +66,7 @@ export = function() { } `; -module.exports = function (initPath) { +export default function (initPath) { const testsPath = getTestRoot(initPath); print(); @@ -135,7 +134,7 @@ module.exports = function (initPath) { }, { name: 'output', - default: './output', + default: './output.js', message: 'Where should logs, screenshots, and reports to be stored?', }, { @@ -345,7 +344,7 @@ module.exports = function (initPath) { await finish(); }); }); -}; +} function install(dependencies) { let command; diff --git a/lib/command/interactive.js b/lib/command/interactive.js index e3a33536a..6b70cbb44 100644 --- a/lib/command/interactive.js +++ b/lib/command/interactive.js @@ -1,12 +1,12 @@ -const { getConfig, getTestRoot } = require('./utils'); -const recorder = require('../recorder'); -const Codecept = require('../codecept'); -const Container = require('../container'); -const event = require('../event'); -const output = require('../output'); -const webHelpers = require('../plugin/standardActingHelpers'); +import { getConfig, getTestRoot } from './utils.js'; +import recorder from '../recorder.js'; +import Codecept from '../codecept'; +import Container from '../container.js'; +import * as event from '../event.js'; +import output from '../output.js'; +import webHelpers from '../plugin/standardActingHelpers.js'; -module.exports = async function (path, options) { +export default async function (path, options) { // Backward compatibility for --profile process.profile = options.profile; process.env.profile = options.profile; @@ -52,4 +52,4 @@ module.exports = async function (path, options) { } catch (err) { output.error(`Error while running bootstrap file :${err}`); } -}; +} diff --git a/lib/command/list.js b/lib/command/list.js index 3a14e5942..85a3e59ee 100644 --- a/lib/command/list.js +++ b/lib/command/list.js @@ -1,11 +1,11 @@ -const { getConfig, getTestRoot } = require('./utils'); -const Codecept = require('../codecept'); -const container = require('../container'); -const { getParamsToString } = require('../parser'); -const { methodsOfObject } = require('../utils'); -const output = require('../output'); +import { getConfig, getTestRoot } from './utils.js'; +import Codecept from '../codecept'; +import container from '../container.js'; +import { getParamsToString } from '../parser.js'; +import { methodsOfObject } from '../utils.js'; +import output from '../output.js'; -module.exports = function (path) { +export default function (path) { const testsPath = getTestRoot(path); const config = getConfig(testsPath); const codecept = new Codecept(config, {}); @@ -33,4 +33,4 @@ module.exports = function (path) { } output.print('PS: Actions are retrieved from enabled helpers. '); output.print('Implement custom actions in your helper classes.'); -}; +} diff --git a/lib/command/run-multiple.js b/lib/command/run-multiple.js index 228cbb36c..eeef2d888 100644 --- a/lib/command/run-multiple.js +++ b/lib/command/run-multiple.js @@ -1,16 +1,14 @@ -const { fork } = require('child_process'); -const path = require('path'); -const crypto = require('crypto'); - -const runHook = require('../hooks'); -const event = require('../event'); -const collection = require('./run-multiple/collection'); -const { clearString, replaceValueDeep } = require('../utils'); -const { - getConfig, getTestRoot, fail, -} = require('./utils'); - -const runner = path.join(__dirname, '/../../bin/codecept'); +import { fork } from 'child_process'; +import path from 'path'; +import crypto from 'crypto'; +import runHook from '../hooks.js'; +import * as event from '../event.js'; +import collection from './run-multiple/collection'; +import { clearString, replaceValueDeep } from '../utils.js'; +import { getConfig, getTestRoot, fail } from './utils.js'; +const __dirname = path.resolve(); + +const runner = path.join(__dirname, '/../../bin/codecept.js'); let config; const childOpts = {}; const copyOptions = ['override', 'steps', 'reporter', 'verbose', 'config', 'reporter-options', 'grep', 'fgrep', 'invert', 'debug', 'plugins', 'colors']; @@ -26,7 +24,7 @@ let subprocessCount = 0; let totalSubprocessCount = 0; let processesDone; -module.exports = async function (selectedRuns, options) { +export default async function (selectedRuns, options) { // registering options globally to use in config if (options.profile) { process.env.profile = options.profile; @@ -108,7 +106,7 @@ module.exports = async function (selectedRuns, options) { await runHook(config.teardownAll, 'teardownAll'); event.emit(event.multiple.after, null); }); -}; +} function executeRun(runName, runConfig) { // clone config diff --git a/lib/command/run-multiple/chunk.js b/lib/command/run-multiple/chunk.js index d57fcafe4..ed1b5fb84 100644 --- a/lib/command/run-multiple/chunk.js +++ b/lib/command/run-multiple/chunk.js @@ -1,6 +1,6 @@ -const glob = require('glob'); -const path = require('path'); -const fs = require('fs'); +import glob from 'glob'; +import path from 'path'; +import fs from 'fs'; /** * Splits a list to (n) parts, defined via the size argument. @@ -61,7 +61,7 @@ const mapFileFormats = (files) => { * files by the passed number or executing a usder deifned function to perform * the splitting. */ -const createChunks = (config, patterns = []) => { +export const createChunks = (config, patterns = []) => { const files = patterns.filter(pattern => !!pattern).map((pattern) => { return findFiles(pattern).filter((file) => { return config.grep ? grepFile(file, config.grep) : true; @@ -86,6 +86,6 @@ const createChunks = (config, patterns = []) => { }); }; -module.exports = { +export default { createChunks, }; diff --git a/lib/command/run-multiple/collection.js b/lib/command/run-multiple/collection.js index a533029d3..e9a3e3368 100644 --- a/lib/command/run-multiple/collection.js +++ b/lib/command/run-multiple/collection.js @@ -1,5 +1,5 @@ -const { createChunks } = require('./chunk'); -const { createRun } = require('./run'); +import { createChunks } from './chunk.js'; +import { createRun } from './run.js'; /** * Bootstraps a collection of runs, it combines user defined selection of runs @@ -190,6 +190,6 @@ function guessBrowser(config) { return [config.helpers[firstHelper].browser]; } -module.exports = { +export default { createRuns, }; diff --git a/lib/command/run-multiple/run.js b/lib/command/run-multiple/run.js index ea06309df..86efdf29b 100644 --- a/lib/command/run-multiple/run.js +++ b/lib/command/run-multiple/run.js @@ -21,10 +21,6 @@ class Run { } } -const createRun = (name, config) => { +export function createRun(name, config) { return new Run(name, config); }; - -module.exports = { - createRun, -}; diff --git a/lib/command/run-rerun.js b/lib/command/run-rerun.js index a104bbaa6..fa9cd0080 100644 --- a/lib/command/run-rerun.js +++ b/lib/command/run-rerun.js @@ -1,9 +1,9 @@ -const { getConfig, getTestRoot } = require('./utils'); -const { printError, createOutputDir } = require('./utils'); -const Config = require('../config'); -const Codecept = require('../rerun'); +import { getConfig, getTestRoot } from './utils.js'; +import { printError, createOutputDir } from './utils.js'; +import Config from '../config.js'; +import Codecept from '../rerun'; -module.exports = async function (test, options) { +export default async function (test, options) { // registering options globally to use in config // Backward compatibility for --profile process.profile = options.profile; @@ -35,4 +35,4 @@ module.exports = async function (test, options) { } finally { await codecept.teardown(); } -}; +} diff --git a/lib/command/run-workers.js b/lib/command/run-workers.js index dea62b48b..84d4bd45f 100644 --- a/lib/command/run-workers.js +++ b/lib/command/run-workers.js @@ -1,10 +1,11 @@ // For Node version >=10.5.0, have to use experimental flag -const { tryOrDefault } = require('../utils'); -const output = require('../output'); -const event = require('../event'); -const Workers = require('../workers'); +import { tryOrDefault } from '../utils.js'; -module.exports = async function (workerCount, selectedRuns, options) { +import output from '../output.js'; +import * as event from '../event.js'; +import Workers from '../workers'; + +export default async function (workerCount, selectedRuns, options) { process.env.profile = options.profile; const suiteArr = []; @@ -109,4 +110,4 @@ module.exports = async function (workerCount, selectedRuns, options) { } finally { await workers.teardownAll(); } -}; +} diff --git a/lib/command/run.js b/lib/command/run.js index f494e6a20..36001eb7f 100644 --- a/lib/command/run.js +++ b/lib/command/run.js @@ -1,10 +1,8 @@ -const { - getConfig, printError, getTestRoot, createOutputDir, -} = require('./utils'); -const Config = require('../config'); -const Codecept = require('../codecept'); +import { getConfig, printError, getTestRoot, createOutputDir } from './utils.js'; +import Config from '../config.js'; +import Codecept from '../codecept'; -module.exports = async function (test, options) { +export default async function (test, options) { // registering options globally to use in config // Backward compatibility for --profile process.profile = options.profile; @@ -42,4 +40,4 @@ module.exports = async function (test, options) { } finally { await codecept.teardown(); } -}; +} diff --git a/lib/command/utils.js b/lib/command/utils.js index ac3cf7fd6..402eb390c 100644 --- a/lib/command/utils.js +++ b/lib/command/utils.js @@ -1,15 +1,14 @@ -const fs = require('fs'); -const path = require('path'); -const util = require('util'); -const mkdirp = require('mkdirp'); - -const output = require('../output'); -const { fileExists, beautify } = require('../utils'); +import fs from 'fs'; +import path from 'path'; +import util from 'util'; +import mkdirp from 'mkdirp'; +import output from '../output.js'; +import { fileExists, beautify } from '../utils.js'; // alias to deep merge -module.exports.deepMerge = require('../utils').deepMerge; +import { deepMerge } from "../utils.js"; -module.exports.getConfig = function (configFile) { +export const getConfig = function (configFile) { try { return require('../config').load(configFile); } catch (err) { @@ -17,7 +16,7 @@ module.exports.getConfig = function (configFile) { } }; -module.exports.readConfig = function (configFile) { +export const readConfig = function (configFile) { try { const data = fs.readFileSync(configFile, 'utf8'); return data; @@ -32,14 +31,14 @@ function getTestRoot(currentPath) { currentPath = fs.lstatSync(currentPath).isDirectory() || !path.extname(currentPath) ? currentPath : path.dirname(currentPath); return currentPath; } -module.exports.getTestRoot = getTestRoot; +export { getTestRoot }; function fail(msg) { output.error(msg); process.exit(1); } -module.exports.fail = fail; +export { fail }; function updateConfig(testsPath, config, key, extension = 'js') { const configFile = path.join(testsPath, `codecept.conf.${extension}`); @@ -57,7 +56,7 @@ function updateConfig(testsPath, config, key, extension = 'js') { return fs.writeFileSync(configFile, beautify(`exports.config = ${util.inspect(config, false, 4, false)}`), 'utf-8'); } -module.exports.updateConfig = updateConfig; +export { updateConfig }; function safeFileWrite(file, contents) { if (fileExists(file)) { @@ -68,9 +67,9 @@ function safeFileWrite(file, contents) { return true; } -module.exports.safeFileWrite = safeFileWrite; +export { safeFileWrite }; -module.exports.captureStream = (stream) => { +export const captureStream = (stream) => { let oldStream; let buffer = ''; @@ -87,14 +86,14 @@ module.exports.captureStream = (stream) => { }; }; -module.exports.printError = (err) => { +export const printError = (err) => { output.print(''); output.error(err.message); output.print(''); output.print(output.colors.grey(err.stack.replace(err.message, ''))); }; -module.exports.createOutputDir = (config, testRoot) => { +export const createOutputDir = (config, testRoot) => { let outputDir; if (path.isAbsolute(config.output)) outputDir = config.output; else outputDir = path.join(testRoot, config.output); diff --git a/lib/command/workers/runTests.js b/lib/command/workers/runTests.js index 13efa1b41..b02a2ee14 100644 --- a/lib/command/workers/runTests.js +++ b/lib/command/workers/runTests.js @@ -8,10 +8,10 @@ if (!tty.getWindowSize) { } const { parentPort, workerData } = require('worker_threads'); -const event = require('../../event'); -const container = require('../../container'); -const { getConfig } = require('../utils'); -const { tryOrDefault, deepMerge } = require('../../utils'); +const event = require('../../event.js'); +const container = require('../../container.js'); +const { getConfig } = require('../utils.js'); +const { tryOrDefault, deepMerge } = require('../../utils.js'); // eslint-disable-next-line no-unused-vars let stdout = ''; diff --git a/lib/config.js b/lib/config.js index 3eaa49e55..a062cc6b8 100644 --- a/lib/config.js +++ b/lib/config.js @@ -1,11 +1,6 @@ -const fs = require('fs'); -const path = require('path'); -const { - fileExists, - isFile, - deepMerge, - deepClone, -} = require('./utils'); +import fs from 'fs'; +import path from 'path'; +import { fileExists, isFile, deepMerge, deepClone } from './utils.js'; const defaultConfig = { output: './_output', @@ -142,7 +137,7 @@ class Config { } } -module.exports = Config; +export default Config; function loadConfigFile(configFile) { const extensionName = path.extname(configFile); @@ -157,7 +152,7 @@ function loadConfigFile(configFile) { // .conf.js config file if (extensionName === '.js' || extensionName === '.ts' || extensionName === '.cjs') { - return Config.create(require(configFile).config); + return Config.create(configFile.config); } // json config provided diff --git a/lib/container.js b/lib/container.js index 9427718e8..177cf81b9 100644 --- a/lib/container.js +++ b/lib/container.js @@ -1,13 +1,13 @@ -const glob = require('glob'); -const path = require('path'); -const { MetaStep } = require('./step'); -const { fileExists, isFunction, isAsyncFunction } = require('./utils'); -const Translation = require('./translation'); -const MochaFactory = require('./mochaFactory'); -const recorder = require('./recorder'); -const event = require('./event'); -const WorkerStorage = require('./workerStorage'); -const store = require('./store'); +import glob from 'glob'; +import path from 'path'; +import { MetaStep } from './step.js'; +import { fileExists, isFunction, isAsyncFunction } from './utils.js'; +import Translation from './translation.js'; +import MochaFactory from './mochaFactory.js'; +import recorder from './recorder.js'; +import * as event from './event.js'; +import WorkerStorage from './workerStorage.js'; +import { store } from './store.js'; let container = { helpers: {}, @@ -117,7 +117,7 @@ class Container { * @param {Object} newContainer */ static append(newContainer) { - const deepMerge = require('./utils').deepMerge; + const deepMerge = require('./utils.js').deepMerge; container = deepMerge(container, newContainer); } @@ -149,7 +149,7 @@ class Container { } } -module.exports = Container; +export default Container; function createHelpers(config) { const helpers = {}; @@ -180,7 +180,7 @@ function createHelpers(config) { const requirements = HelperClass._checkRequirements(); if (requirements) { let install; - if (require('./utils').installedLocally()) { + if (require('./utils.js').installedLocally()) { install = `npm install --save-dev ${requirements.join(' ')}`; } else { console.log('WARNING: CodeceptJS is not installed locally. It is recommended to switch to local installation'); diff --git a/lib/data/context.js b/lib/data/context.js index 4d6d21bdf..bbcdcfb0c 100644 --- a/lib/data/context.js +++ b/lib/data/context.js @@ -1,9 +1,8 @@ -const { isGenerator } = require('../utils'); -const DataTable = require('./table'); -const DataScenarioConfig = require('./dataScenarioConfig'); -const Secret = require('../secret'); +import { isGenerator } from '../utils.js'; +import DataTable from './table.js'; +import DataScenarioConfig from './dataScenarioConfig.js'; -module.exports = function (context) { +export default function (context) { context.Data = function (dataTable) { const data = detectDataType(dataTable); return { @@ -62,7 +61,7 @@ module.exports = function (context) { }, }; }; -}; +} function replaceTitle(title, dataRow) { if (typeof dataRow.data !== 'object') { diff --git a/lib/data/dataScenarioConfig.js b/lib/data/dataScenarioConfig.js index 9cb9173f7..46a8f5ff8 100644 --- a/lib/data/dataScenarioConfig.js +++ b/lib/data/dataScenarioConfig.js @@ -81,4 +81,4 @@ class DataScenarioConfig { } } -module.exports = DataScenarioConfig; +export default DataScenarioConfig; diff --git a/lib/data/dataTableArgument.js b/lib/data/dataTableArgument.js index b32953483..ab9c66e43 100644 --- a/lib/data/dataTableArgument.js +++ b/lib/data/dataTableArgument.js @@ -63,4 +63,4 @@ class DataTableArgument { } } -module.exports = DataTableArgument; +export default DataTableArgument; diff --git a/lib/data/table.js b/lib/data/table.js index 20981a65a..f97db1984 100644 --- a/lib/data/table.js +++ b/lib/data/table.js @@ -40,4 +40,4 @@ class DataTable { } } -module.exports = DataTable; +export default DataTable; diff --git a/lib/event.js b/lib/event.js index 676354be7..3a8d73a18 100644 --- a/lib/event.js +++ b/lib/event.js @@ -1,172 +1,176 @@ -const debug = require('debug')('codeceptjs:event'); -const events = require('events'); -const { error } = require('./output'); +import debug from 'debug'; + +import events from 'events'; +import { error } from './output.js'; + +debug('codeceptjs:event'); const dispatcher = new events.EventEmitter(); dispatcher.setMaxListeners(50); + /** - * @namespace - * @alias event + * @type {object} + * @constant + * @inner + * @property {'test.start'} started + * @property {'test.before'} before + * @property {'test.after'} after + * @property {'test.passed'} passed + * @property {'test.failed'} failed + * @property {'test.finish'} finished + * @property {'test.skipped'} skipped */ -module.exports = { - /** - * @type {NodeJS.EventEmitter} - * @constant - * @inner - */ - dispatcher, - /** - * @type {object} - * @constant - * @inner - * @property {'test.start'} started - * @property {'test.before'} before - * @property {'test.after'} after - * @property {'test.passed'} passed - * @property {'test.failed'} failed - * @property {'test.finish'} finished - * @property {'test.skipped'} skipped - */ - test: { - started: 'test.start', // sync - before: 'test.before', // async - after: 'test.after', // async - passed: 'test.passed', // sync - failed: 'test.failed', // sync - finished: 'test.finish', // sync - skipped: 'test.skipped', // sync - }, - /** - * @type {object} - * @constant - * @inner - * @property {'suite.before'} before - * @property {'suite.after'} after - */ - suite: { - before: 'suite.before', - after: 'suite.after', - }, - /** - * @type {object} - * @constant - * @inner - * @property {'hook.start'} started - * @property {'hook.passed'} passed - */ - hook: { - started: 'hook.start', - passed: 'hook.passed', - failed: 'hook.failed', - }, - /** - * @type {object} - * @constant - * @inner - * @property {'step.start'} started - * @property {'step.before'} before - * @property {'step.after'} after - * @property {'step.passed'} passed - * @property {'step.failed'} failed - * @property {'step.finish'} finished - * @property {'step.comment'} comment - */ - step: { - before: 'step.before', // async - after: 'step.after', // async - started: 'step.start', // sync - passed: 'step.passed', // sync - failed: 'step.failed', // sync - finished: 'step.finish', // sync - comment: 'step.comment', - }, - /** - * @type {object} - * @constant - * @inner - * @property {'suite.before'} before - * @property {'suite.after'} after - */ - bddStep: { - before: 'bddStep.before', - after: 'bddStep.after', - started: 'bddStep.started', - finished: 'bddStep.finished', - }, - /** - * @type {object} - * @constant - * @inner - * @property {'global.before'} before - * @property {'global.after'} after - * @property {'global.result'} result - * @property {'global.failures'} failures - */ - all: { - before: 'global.before', - after: 'global.after', - result: 'global.result', - failures: 'global.failures', - }, - /** - * @type {object} - * @constant - * @inner - * @property {'multiple.before'} before - * @property {'multiple.after'} after - */ - multiple: { - before: 'multiple.before', - after: 'multiple.after', - }, - - /** - * @type {object} - * @constant - * @inner - * @property {'workers.before'} before - * @property {'workers.after'} after - * @property {'workers.result'} result - */ - workers: { - before: 'workers.before', - after: 'workers.after', - result: 'workers.result', - }, +export const test = { + started: 'test.start', // sync + before: 'test.before', // async + after: 'test.after', // async + passed: 'test.passed', // sync + failed: 'test.failed', // sync + finished: 'test.finish', // sync + skipped: 'test.skipped', // sync +}; - /** - * @param {string} event - * @param {*} [param] - */ - emit(event, param) { - let msg = `Emitted | ${event}`; - if (param && param.toString()) { - msg += ` (${param.toString()})`; - } - debug(msg); - try { - this.dispatcher.emit.apply(this.dispatcher, arguments); - } catch (err) { - error(`Error processing ${event} event:`); - error(err.stack); - } - }, +/** + * @type {object} + * @constant + * @inner + * @property {'suite.before'} before + * @property {'suite.after'} after + */ +export const suite = { + before: 'suite.before', + after: 'suite.after', +}; +/** + * @type {object} + * @constant + * @inner + * @property {'hook.start'} started + * @property {'hook.passed'} passed + */ +export const hook = { + started: 'hook.start', + passed: 'hook.passed', + failed: 'hook.failed', +}; +/** + * @type {object} + * @constant + * @inner + * @property {'step.start'} started + * @property {'step.before'} before + * @property {'step.after'} after + * @property {'step.passed'} passed + * @property {'step.failed'} failed + * @property {'step.finish'} finished + * @property {'step.comment'} comment + */ +export const step = { + before: 'step.before', // async + after: 'step.after', // async + started: 'step.start', // sync + passed: 'step.passed', // sync + failed: 'step.failed', // sync + finished: 'step.finish', // sync + comment: 'step.comment', +}; +/** + * @type {object} + * @constant + * @inner + * @property {'suite.before'} before + * @property {'suite.after'} after + */ +export const bddStep = { + before: 'bddStep.before', + after: 'bddStep.after', + started: 'bddStep.started', + finished: 'bddStep.finished', +}; +/** + * @type {object} + * @constant + * @inner + * @property {'global.before'} before + * @property {'global.after'} after + * @property {'global.result'} result + * @property {'global.failures'} failures + */ +export const all = { + before: 'global.before', + after: 'global.after', + result: 'global.result', + failures: 'global.failures', +}; +/** + * @type {object} + * @constant + * @inner + * @property {'multiple.before'} before + * @property {'multiple.after'} after + */ +export const multiple = { + before: 'multiple.before', + after: 'multiple.after', +}; - /** for testing only! */ - cleanDispatcher: () => { - let event; - for (event in this.test) { - this.dispatcher.removeAllListeners(this.test[event]); - } - for (event in this.suite) { - this.dispatcher.removeAllListeners(this.test[event]); - } - for (event in this.step) { - this.dispatcher.removeAllListeners(this.test[event]); - } - for (event in this.all) { - this.dispatcher.removeAllListeners(this.test[event]); - } - }, +/** + * @type {object} + * @constant + * @inner + * @property {'workers.before'} before + * @property {'workers.after'} after + * @property {'workers.result'} result + */ +export const workers = { + before: 'workers.before', + after: 'workers.after', + result: 'workers.result', }; + +/** for testing only! */ +export function cleanDispatcher() { + let event; + for (event in test) { + dispatcher.removeAllListeners(test[event]); + } + for (event in suite) { + dispatcher.removeAllListeners(test[event]); + } + for (event in step) { + dispatcher.removeAllListeners(test[event]); + } + for (event in all) { + dispatcher.removeAllListeners(test[event]); + } +} + +/** + * @namespace + * @alias event + */ +/** + * @type {NodeJS.EventEmitter} + * @constant + * @inner + */ +export { dispatcher }; + +/** + * @param {string} event + * @param {*} [param] + */ +export function emit(event, param) { + let msg = `Emitted | ${event}`; + if (param && param.toString()) { + msg += ` (${param.toString()})`; + } + debug(msg); + try { + dispatcher.emit.apply(dispatcher, arguments); + } catch (err) { + error(`Error processing ${event} event:`); + error(err.stack); + } +} diff --git a/lib/helper.js b/lib/helper.js index 3919046d1..3804e0695 100644 --- a/lib/helper.js +++ b/lib/helper.js @@ -1,2 +1,4 @@ // helper class was moved out from this repository to allow extending from base class -module.exports = require('@codeceptjs/helper'); +import generated from '@codeceptjs/helper'; + +export default generated; diff --git a/lib/helper/ApiDataFactory.js b/lib/helper/ApiDataFactory.js index e8f9c5dd6..9f8b71011 100644 --- a/lib/helper/ApiDataFactory.js +++ b/lib/helper/ApiDataFactory.js @@ -1,7 +1,6 @@ -const path = require('path'); - -const Helper = require('@codeceptjs/helper'); -const REST = require('./REST'); +import path from 'path'; +import Helper from '@codeceptjs/helper'; +import REST from './REST'; /** * Helper for managing remote data using REST API. @@ -402,7 +401,7 @@ Current file error: ${err.message}`); } } -module.exports = ApiDataFactory; +export default ApiDataFactory; function createRequestFromFunction(param, data) { if (typeof param !== 'function') return; diff --git a/lib/helper/Appium.js b/lib/helper/Appium.js index b6f2953c4..bd6f2beb8 100644 --- a/lib/helper/Appium.js +++ b/lib/helper/Appium.js @@ -1,15 +1,14 @@ let webdriverio; -const fs = require('fs'); -const axios = require('axios').default; -const { v4: uuidv4 } = require('uuid'); - -const Webdriver = require('./WebDriver'); -const AssertionFailedError = require('../assert/error'); -const { truth } = require('../assert/truth'); -const recorder = require('../recorder'); -const Locator = require('../locator'); -const ConnectionRefused = require('./errors/ConnectionRefused'); +import fs from 'fs'; +import { default as axios } from 'axios'; +import { v4 as uuidv4 } from 'uuid'; +import Webdriver from './WebDriver'; +import AssertionFailedError from '../assert/error.js'; +import { truth } from '../assert/truth'; +import recorder from '../recorder.js'; +import Locator from '../locator.js'; +import ConnectionRefused from './errors/ConnectionRefused.js'; const mobileRoot = '//*'; const webRoot = 'body'; @@ -1763,4 +1762,4 @@ function onlyForApps(expectedPlatform) { } } -module.exports = Appium; +export default Appium; diff --git a/lib/helper/Expect.js b/lib/helper/Expect.js index f9cb3e3bf..56ebf41df 100644 --- a/lib/helper/Expect.js +++ b/lib/helper/Expect.js @@ -1,4 +1,4 @@ -const output = require('../output'); +import output from '../output.js'; let expect; @@ -422,4 +422,4 @@ class ExpectHelper { } } -module.exports = ExpectHelper; +export default ExpectHelper; diff --git a/lib/helper/FileSystem.js b/lib/helper/FileSystem.js index 830936c7d..c97846ef0 100644 --- a/lib/helper/FileSystem.js +++ b/lib/helper/FileSystem.js @@ -1,11 +1,11 @@ -const assert = require('assert'); -const path = require('path'); -const fs = require('fs'); - -const Helper = require('@codeceptjs/helper'); -const { fileExists } = require('../utils'); -const { fileIncludes } = require('../assert/include'); -const { fileEquals } = require('../assert/equal'); +import assert from 'assert'; +import path from 'path'; +import fs from 'fs'; +import Helper from '@codeceptjs/helper'; +import { fileExists } from '../utils.js'; +import { fileIncludes } from '../assert/include.js'; +import { fileEquals } from '../assert/equal.js'; +import {debugSection} from "../output.js"; /** * Helper for testing filesystem. @@ -30,15 +30,15 @@ const { fileEquals } = require('../assert/equal'); * * ## Methods */ -class FileSystem extends Helper { - constructor() { - super(); +export default class FileSystem extends Helper { + constructor(config) { + super(config); this.dir = global.codecept_dir; this.file = ''; } _before() { - this.debugSection('Dir', this.dir); + debugSection('Dir', this.dir); } /** @@ -48,7 +48,7 @@ class FileSystem extends Helper { */ amInPath(openPath) { this.dir = path.join(global.codecept_dir, openPath); - this.debugSection('Dir', this.dir); + debugSection('Dir', this.dir); } /** @@ -66,7 +66,7 @@ class FileSystem extends Helper { */ seeFile(name) { this.file = path.join(this.dir, name); - this.debugSection('File', this.file); + debugSection('File', this.file); assert.ok(fileExists(this.file), `File ${name} not found in ${this.dir}`); } @@ -86,7 +86,7 @@ class FileSystem extends Helper { if (sec === 0) assert.fail('Use `seeFile` instead of waiting 0 seconds!'); const waitTimeout = sec * 1000; this.file = path.join(this.dir, name); - this.debugSection('File', this.file); + debugSection('File', this.file); return isFileExists(this.file, waitTimeout).catch(() => { throw new Error(`file (${name}) still not present in directory ${this.dir} after ${waitTimeout / 1000} sec`); }); @@ -180,8 +180,6 @@ class FileSystem extends Helper { } } -module.exports = FileSystem; - /** * @param {string} file * @param {string} [encoding='utf8'] diff --git a/lib/helper/GraphQL.js b/lib/helper/GraphQL.js index fb87f16a2..4a17f0722 100644 --- a/lib/helper/GraphQL.js +++ b/lib/helper/GraphQL.js @@ -1,5 +1,5 @@ -const axios = require('axios').default; -const Helper = require('@codeceptjs/helper'); +import { default as axios } from 'axios'; +import Helper from '@codeceptjs/helper'; /** * GraphQL helper allows to send additional requests to a GraphQl endpoint during acceptance tests. @@ -226,4 +226,4 @@ class GraphQL extends Helper { this.haveRequestHeaders({ Authorization: `Bearer ${accessToken}` }); } } -module.exports = GraphQL; +export default GraphQL; diff --git a/lib/helper/GraphQLDataFactory.js b/lib/helper/GraphQLDataFactory.js index 9a6d802e6..c241774f9 100644 --- a/lib/helper/GraphQLDataFactory.js +++ b/lib/helper/GraphQLDataFactory.js @@ -1,7 +1,6 @@ -const path = require('path'); - -const Helper = require('@codeceptjs/helper'); -const GraphQL = require('./GraphQL'); +import path from 'path'; +import Helper from '@codeceptjs/helper'; +import GraphQL from './GraphQL'; /** * Helper for managing remote data using GraphQL queries. @@ -306,4 +305,4 @@ class GraphQLDataFactory extends Helper { } } -module.exports = GraphQLDataFactory; +export default GraphQLDataFactory; diff --git a/lib/helper/JSONResponse.js b/lib/helper/JSONResponse.js index e651a6833..6a617b2c3 100644 --- a/lib/helper/JSONResponse.js +++ b/lib/helper/JSONResponse.js @@ -1,4 +1,4 @@ -const Helper = require('@codeceptjs/helper'); +import Helper from '@codeceptjs/helper'; let expect; @@ -7,7 +7,7 @@ import('chai').then(chai => { chai.use(require('chai-deep-match')); }); -const joi = require('joi'); +import joi from 'joi'; /** * This helper allows performing assertions on JSON responses paired with following helpers: @@ -335,4 +335,4 @@ class JSONResponse extends Helper { } } -module.exports = JSONResponse; +export default JSONResponse; diff --git a/lib/helper/Mochawesome.js b/lib/helper/Mochawesome.js index 826b2f232..6330d8383 100644 --- a/lib/helper/Mochawesome.js +++ b/lib/helper/Mochawesome.js @@ -2,8 +2,8 @@ let addMochawesomeContext; let currentTest; let currentSuite; -const Helper = require('@codeceptjs/helper'); -const { clearString } = require('../utils'); +import Helper from '@codeceptjs/helper'; +import { clearString } from '../utils.js'; class Mochawesome extends Helper { constructor(config) { @@ -68,4 +68,4 @@ class Mochawesome extends Helper { } } -module.exports = Mochawesome; +export default Mochawesome; diff --git a/lib/helper/MockServer.js b/lib/helper/MockServer.js index 9cb748808..41e389529 100644 --- a/lib/helper/MockServer.js +++ b/lib/helper/MockServer.js @@ -1,4 +1,4 @@ -const { mock, settings } = require('pactum'); +import { mock, settings } from 'pactum'; /** * ## Configuration @@ -218,4 +218,4 @@ class MockServer { } } -module.exports = MockServer; +export default MockServer; diff --git a/lib/helper/Nightmare.js b/lib/helper/Nightmare.js index 59947bec6..6a8f3eb14 100644 --- a/lib/helper/Nightmare.js +++ b/lib/helper/Nightmare.js @@ -1,21 +1,16 @@ -const path = require('path'); - -const urlResolve = require('url').resolve; - -const Helper = require('@codeceptjs/helper'); -const { includes: stringIncludes } = require('../assert/include'); -const { urlEquals } = require('../assert/equal'); -const { equals } = require('../assert/equal'); -const { empty } = require('../assert/empty'); -const { truth } = require('../assert/truth'); -const Locator = require('../locator'); -const ElementNotFound = require('./errors/ElementNotFound'); -const { - xpathLocator, - fileExists, - screenshotOutputFolder, - toCamelCase, -} = require('../utils'); +import path from 'path'; + +import { resolve as urlResolve } from 'url'; + +import Helper from '@codeceptjs/helper'; +import { includes as stringIncludes } from '../assert/include.js'; +import { urlEquals } from '../assert/equal.js'; +import { equals } from '../assert/equal.js'; +import { empty } from '../assert/empty.js'; +import { truth } from '../assert/truth'; +import Locator from '../locator.js'; +import ElementNotFound from './errors/ElementNotFound.js'; +import { xpathLocator, fileExists, screenshotOutputFolder, toCamelCase } from '../utils.js'; const specialKeys = { Backspace: '\u0008', @@ -1289,7 +1284,7 @@ class Nightmare extends Helper { } } -module.exports = Nightmare; +export default Nightmare; async function proceedSee(assertType, text, context) { let description; diff --git a/lib/helper/OpenAI.js b/lib/helper/OpenAI.js index 806008ba4..01e5f5ee1 100644 --- a/lib/helper/OpenAI.js +++ b/lib/helper/OpenAI.js @@ -1,8 +1,8 @@ -const Helper = require('@codeceptjs/helper'); -const AiAssistant = require('../ai'); -const standardActingHelpers = require('../plugin/standardActingHelpers'); -const Container = require('../container'); -const { splitByChunks, minifyHtml } = require('../html'); +import Helper from '@codeceptjs/helper'; +import AiAssistant from '../ai'; +import standardActingHelpers from '../plugin/standardActingHelpers.js'; +import Container from '../container.js'; +import { splitByChunks, minifyHtml } from '../html'; /** * OpenAI Helper for CodeceptJS. @@ -123,4 +123,4 @@ class OpenAI extends Helper { } } -module.exports = OpenAI; +export default OpenAI; diff --git a/lib/helper/Playwright.js b/lib/helper/Playwright.js index 4c39b9682..c1b7a429b 100644 --- a/lib/helper/Playwright.js +++ b/lib/helper/Playwright.js @@ -1,18 +1,18 @@ -const path = require('path'); -const fs = require('fs'); - -const Helper = require('@codeceptjs/helper'); -const { v4: uuidv4 } = require('uuid'); -const assert = require('assert'); -const promiseRetry = require('promise-retry'); -const Locator = require('../locator'); -const recorder = require('../recorder'); -const stringIncludes = require('../assert/include').includes; -const { urlEquals } = require('../assert/equal'); -const { equals } = require('../assert/equal'); -const { empty } = require('../assert/empty'); -const { truth } = require('../assert/truth'); -const { +import path from 'path'; +import fs from 'fs'; +import Helper from '@codeceptjs/helper'; +import { v4 as uuidv4 } from 'uuid'; +import assert from 'assert'; +import promiseRetry from 'promise-retry'; +import Locator from '../locator.js'; +import recorder from '../recorder.js'; +import { includes as stringIncludes } from '../assert/include.js'; +import { urlEquals } from '../assert/equal.js'; +import { equals } from '../assert/equal.js'; +import { empty } from '../assert/empty.js'; +import { truth } from '../assert/truth'; + +import { xpathLocator, ucfirst, fileExists, @@ -24,16 +24,14 @@ const { clearString, requireWithFallback, normalizeSpacesInString, -} = require('../utils'); -const { - isColorProperty, - convertColorToRGBA, -} = require('../colorUtils'); -const ElementNotFound = require('./errors/ElementNotFound'); -const RemoteBrowserConnectionRefused = require('./errors/RemoteBrowserConnectionRefused'); -const Popup = require('./extras/Popup'); -const Console = require('./extras/Console'); -const { findReact, findVue } = require('./extras/PlaywrightReactVueLocator'); +} from '../utils.js'; + +import { isColorProperty, convertColorToRGBA } from '../colorUtils'; +import ElementNotFound from './errors/ElementNotFound.js'; +import RemoteBrowserConnectionRefused from './errors/RemoteBrowserConnectionRefused'; +import Popup from './extras/Popup'; +import Console from './extras/Console'; +import { findReact, findVue } from './extras/PlaywrightReactVueLocator'; let playwright; let perfTiming; @@ -43,15 +41,23 @@ const popupStore = new Popup(); const consoleLogStore = new Console(); const availableBrowsers = ['chromium', 'webkit', 'firefox', 'electron']; -const { - setRestartStrategy, restartsSession, restartsContext, restartsBrowser, -} = require('./extras/PlaywrightRestartOpts'); -const { createValueEngine, createDisabledEngine } = require('./extras/PlaywrightPropEngine'); -const { - seeElementError, dontSeeElementError, dontSeeElementInDOMError, seeElementInDOMError, -} = require('./errors/ElementAssertion'); -const { createAdvancedTestResults, allParameterValuePairsMatchExtreme, extractQueryObjects } = require('./networkTraffics/utils'); -const { log } = require('../output'); +import { setRestartStrategy, restartsSession, restartsContext, restartsBrowser } from './extras/PlaywrightRestartOpts'; +import { createValueEngine, createDisabledEngine } from './extras/PlaywrightPropEngine'; + +import { + seeElementError, + dontSeeElementError, + dontSeeElementInDOMError, + seeElementInDOMError, +} from './errors/ElementAssertion'; + +import { + createAdvancedTestResults, + allParameterValuePairsMatchExtreme, + extractQueryObjects, +} from './networkTraffics/utils.js'; + +import { log } from '../output.js'; const pathSeparator = path.sep; @@ -534,7 +540,7 @@ class Playwright extends Helper { } else { try { const existingPages = await this.browserContext.pages(); - mainPage = existingPages[0] || await this.browserContext.newPage(); + mainPage = existingPages[0] || (await this.browserContext.newPage()); } catch (e) { if (this.playwrightOptions.userDataDir) { this.browser = await playwright[this.options.browser].launchPersistentContext(this.userDataDir, this.playwrightOptions); @@ -1253,7 +1259,7 @@ class Playwright extends Helper { * ``` */ async _locate(locator) { - const context = await this.context || await this._getContext(); + const context = (await this.context) || (await this._getContext()); if (this.frame) return findElements(this.frame, locator); @@ -1269,7 +1275,7 @@ class Playwright extends Helper { * ``` */ async _locateElement(locator) { - const context = await this.context || await this._getContext(); + const context = (await this.context) || (await this._getContext()); return findElement(context, locator); } @@ -1282,7 +1288,7 @@ class Playwright extends Helper { * ``` */ async _locateCheckable(locator, providedContext = null) { - const context = providedContext || await this._getContext(); + const context = providedContext || (await this._getContext()); const els = await findCheckable.call(this, locator, context); assertElementExists(els[0], locator, 'Checkbox or radio'); return els[0]; @@ -3441,7 +3447,7 @@ class Playwright extends Helper { } } -module.exports = Playwright; +export default Playwright; function buildLocatorString(locator) { if (locator.isCustom()) { diff --git a/lib/helper/Protractor.js b/lib/helper/Protractor.js index 1d2a42d26..23de6fee7 100644 --- a/lib/helper/Protractor.js +++ b/lib/helper/Protractor.js @@ -4,26 +4,24 @@ let Button; let ProtractorBy; let ProtractorExpectedConditions; -const path = require('path'); - -const Helper = require('@codeceptjs/helper'); -const stringIncludes = require('../assert/include').includes; -const { urlEquals, equals } = require('../assert/equal'); -const { empty } = require('../assert/empty'); -const { truth } = require('../assert/truth'); -const { +import path from 'path'; +import Helper from '@codeceptjs/helper'; +import { includes as stringIncludes } from '../assert/include.js'; +import { urlEquals, equals } from '../assert/equal.js'; +import { empty } from '../assert/empty.js'; +import { truth } from '../assert/truth'; + +import { xpathLocator, fileExists, convertCssPropertiesToCamelCase, screenshotOutputFolder, -} = require('../utils'); -const { - isColorProperty, - convertColorToRGBA, -} = require('../colorUtils'); -const ElementNotFound = require('./errors/ElementNotFound'); -const ConnectionRefused = require('./errors/ConnectionRefused'); -const Locator = require('../locator'); +} from '../utils.js'; + +import { isColorProperty, convertColorToRGBA } from '../colorUtils'; +import ElementNotFound from './errors/ElementNotFound.js'; +import ConnectionRefused from './errors/ConnectionRefused.js'; +import Locator from '../locator.js'; let withinStore = {}; let Runner; @@ -1676,7 +1674,7 @@ class Protractor extends Helper { } } -module.exports = Protractor; +export default Protractor; async function findCheckable(client, locator) { const matchedLocator = guessLocator(locator); diff --git a/lib/helper/Puppeteer.js b/lib/helper/Puppeteer.js index ca82e163d..53ec602f7 100644 --- a/lib/helper/Puppeteer.js +++ b/lib/helper/Puppeteer.js @@ -1,21 +1,21 @@ -const axios = require('axios'); -const fs = require('fs'); -const fsExtra = require('fs-extra'); -const path = require('path'); - -const Helper = require('@codeceptjs/helper'); -const { v4: uuidv4 } = require('uuid'); -const promiseRetry = require('promise-retry'); -const Locator = require('../locator'); -const recorder = require('../recorder'); -const store = require('../store'); -const stringIncludes = require('../assert/include').includes; -const { urlEquals } = require('../assert/equal'); -const { equals } = require('../assert/equal'); -const { empty } = require('../assert/empty'); -const { truth } = require('../assert/truth'); -const isElementClickable = require('./scripts/isElementClickable'); -const { +import axios from 'axios'; +import fs from 'fs'; +import fsExtra from 'fs-extra'; +import path from 'path'; +import Helper from '@codeceptjs/helper'; +import { v4 as uuidv4 } from 'uuid'; +import promiseRetry from 'promise-retry'; +import Locator from '../locator.js'; +import recorder from '../recorder.js'; +import { store } from '../store.js'; +import { includes as stringIncludes } from '../assert/include.js'; +import { urlEquals } from '../assert/equal.js'; +import { equals } from '../assert/equal.js'; +import { empty } from '../assert/empty.js'; +import { truth } from '../assert/truth'; +import isElementClickable from './scripts/isElementClickable'; + +import { xpathLocator, ucfirst, fileExists, @@ -26,23 +26,26 @@ const { screenshotOutputFolder, getNormalizedKeyAttributeValue, isModifierKey, - requireWithFallback, normalizeSpacesInString, -} = require('../utils'); -const { - isColorProperty, - convertColorToRGBA, -} = require('../colorUtils'); -const ElementNotFound = require('./errors/ElementNotFound'); -const RemoteBrowserConnectionRefused = require('./errors/RemoteBrowserConnectionRefused'); -const Popup = require('./extras/Popup'); -const Console = require('./extras/Console'); -const findReact = require('./extras/React'); -const { highlightElement } = require('./scripts/highlightElement'); -const { blurElement } = require('./scripts/blurElement'); -const { focusElement } = require('./scripts/focusElement'); -const { - dontSeeElementError, seeElementError, dontSeeElementInDOMError, seeElementInDOMError, -} = require('./errors/ElementAssertion'); + requireWithFallback, + normalizeSpacesInString, +} from '../utils.js'; + +import { isColorProperty, convertColorToRGBA } from '../colorUtils'; +import ElementNotFound from './errors/ElementNotFound.js'; +import RemoteBrowserConnectionRefused from './errors/RemoteBrowserConnectionRefused'; +import Popup from './extras/Popup'; +import Console from './extras/Console'; +import findReact from './extras/React'; +import { highlightElement } from './scripts/highlightElement'; +import { blurElement } from './scripts/blurElement'; +import { focusElement } from './scripts/focusElement'; + +import { + dontSeeElementError, + seeElementError, + dontSeeElementInDOMError, + seeElementInDOMError, +} from './errors/ElementAssertion'; let puppeteer; let perfTiming; @@ -574,7 +577,7 @@ class Puppeteer extends Helper { }); const existingPages = await this.browser.pages(); - const mainPage = existingPages[0] || await this.browser.newPage(); + const mainPage = existingPages[0] || (await this.browser.newPage()); if (existingPages.length) { // Run the handler as it will not be triggered if the page already exists @@ -896,7 +899,7 @@ class Puppeteer extends Helper { * ``` */ async _locateCheckable(locator, providedContext = null) { - const context = providedContext || await this._getContext(); + const context = providedContext || (await this._getContext()); const els = await findCheckable.call(this, locator, context); assertElementExists(els[0], locator, 'Checkbox or radio'); return els[0]; @@ -1440,7 +1443,7 @@ class Puppeteer extends Helper { const els = await findVisibleFields.call(this, select); assertElementExists(els, select, 'Selectable field'); const el = els[0]; - if (await el.getProperty('tagName').then(t => t.jsonValue()) !== 'SELECT') { + if ((await el.getProperty('tagName').then(t => t.jsonValue())) !== 'SELECT') { throw new Error('Element is not