8000 Moved JsTrait methods to ElementTrait. by AlexSkrypnyk · Pull Request #370 · drevops/behat-steps · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Moved JsTrait methods to ElementTrait. #370

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 30, 2025
Merged

Conversation

AlexSkrypnyk
Copy link
Member
@AlexSkrypnyk AlexSkrypnyk commented Apr 30, 2025

Summary by CodeRabbit

  • New Features

    • Added new step definitions for interacting with and asserting properties of HTML elements during testing, including clicking elements, triggering events, handling confirmation dialogs, scrolling to elements, and verifying element position in the viewport.
  • Bug Fixes

    • Enhanced screenshot capture on test failures, now supporting fullscreen mode and additional metadata for improved debugging.
  • Documentation

    • Updated documentation to reflect the relocation of JavaScript interaction steps from one section to another for clarity.
  • Tests

    • Added new feature scenarios to test interactive behaviors and element assertions.
    • Removed redundant or relocated JavaScript feature tests.
  • Chores

    • Updated development dependencies to newer versions.

Copy link
coderabbitai bot commented Apr 30, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

🗂️ Base branches to auto review (3)
  • main
  • develop
  • master

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This change migrates JavaScript-related step definitions and helper methods from the now-removed JsTrait to the ElementTrait trait, consolidating all element and JavaScript interaction logic. The documentation and feature tests have been updated to reflect this migration, with the relevant scenarios moved from js.feature to element.feature. Configuration for the screenshot extension in behat.yml was enhanced with new options, and the screenshot extension dependency was updated in composer.json.

Changes

File(s) Change Summary
src/JsTrait.php Removed the JsTrait trait, which previously provided JavaScript-related step definitions and helpers for browser interaction.
src/ElementTrait.php Added multiple new methods for JavaScript and element interaction, previously found in JsTrait. These include methods for confirmation dialogs, event triggering, scrolling, and assertions.
steps.md Moved all JavaScript-related step documentation from the JsTrait section to the ElementTrait section; removed JsTrait from the table of contents.
tests/behat/bootstrap/FeatureContext.php Removed the import and usage of JsTrait from the Behat context class.
tests/behat/features/js.feature Deleted feature file containing JavaScript interaction scenarios; these scenarios were moved to element.feature.
tests/behat/features/element.feature Added new scenarios for JavaScript interactions (click, event trigger, confirmation dialogs, scrolling) previously found in js.feature.
behat.yml Enhanced screenshot extension configuration with new options for automatic failure capture, fullscreen mode, algorithm selection, and metadata enrichment.
tests/behat/fixtures/d10/composer.json Updated the drevops/behat-screenshot development dependency version from ^1.6 to ^2.1.

Sequence Diagram(s)

sequenceDiagram
    participant Tester as Behat Tester
    participant ElementTrait as ElementTrait
    participant Browser as Browser Session

    Tester->>ElementTrait: Call step (e.g., "I accept all confirmations")
    ElementTrait->>Browser: Execute JS (e.g., override window.confirm)
    Browser-->>ElementTrait: JS execution result
    ElementTrait-->>Tester: Step completes

    Tester->>ElementTrait: Call step (e.g., "I click on element '.selector'")
    ElementTrait->>Browser: Find and click element via JS
    Browser-->>ElementTrait: JS execution result
    ElementTrait-->>Tester: Step completes

    Tester->>ElementTrait: Call step (e.g., "I trigger 'click' event on '.selector'")
    ElementTrait->>Browser: Trigger event via JS
    Browser-->>ElementTrait: JS execution result
    ElementTrait-->>Tester: Step completes
Loading

Possibly related PRs

  • [#288]: Updated JSTrait. #358: Updates and refines JavaScript step definitions and methods within JsTrait; both PRs modify the same JavaScript interaction functionality, but this PR restructures and relocates it.

Suggested labels

PR: Requires more work


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@AlexSkrypnyk
Copy link
Member Author

@coderabbitai full review

8000

Copy link
coderabbitai bot commented Apr 30, 2025
✅ Actions performed

Full review triggered.

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9bcb95a and 76ba819.

📒 Files selected for processing (8)
  • behat.yml (1 hunks)
  • src/ElementTrait.php (1 hunks)
  • src/JsTrait.php (0 hunks)
  • steps.md (2 hunks)
  • tests/behat/bootstrap/FeatureContext.php (0 hunks)
  • tests/behat/features/element.feature (1 hunks)
  • tests/behat/features/js.feature (0 hunks)
  • tests/behat/fixtures/d10/composer.json (1 hunks)
💤 Files with no reviewable changes (3)
  • tests/behat/bootstrap/FeatureContext.php
  • tests/behat/features/js.feature
  • src/JsTrait.php
🧰 Additional context used
🪛 YAMLlint (1.35.1)
behat.yml

[warning] 74-74: too few spaces before comment

(comments)

🪛 markdownlint-cli2 (0.17.2)
steps.md

594-594: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)


596-596: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)


604-604: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)


606-606: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)


614-614: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)


616-616: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)

🔇 Additional comments (7)
tests/behat/fixtures/d10/composer.json (1)

48-48: Dependency version upgrade - appropriate for the expanded features

The update of drevops/behat-screenshot from a previous version (not shown) to ^2.1 aligns with the enhanced screenshot configuration in behat.yml, where new features like automatic capture on failure, fullscreen options, and additional metadata are being utilized.

behat.yml (1)

72-79: Enhanced screenshot configuration improves test debugging

These additions effectively enhance the screenshot capabilities by:

  1. Automatically capturing screenshots on test failures
  2. Ensuring fullscreen captures with a specified algorithm
  3. Adding rich contextual metadata (URL, feature, step info, timestamp)

All these improvements will help with debugging JavaScript interactions that were migrated from JsTrait to ElementTrait.

#!/bin/bash
# Verify the DrevOps\BehatScreenshotExtension supports these new options

ast-grep --pattern $'DrevOps\\\\BehatScreenshotExtension(.*)\{
  $$$
  (on_failed|always_fullscreen|fullscreen_algorithm|info_types)
  $$$
\}'
🧰 Tools
🪛 YAMLlint (1.35.1)

[warning] 74-74: too few spaces before comment

(comments)

tests/behat/features/element.feature (5)

203-207: Click element test properly implements the migrated function

This scenario effectively tests the element click functionality that was migrated from JsTrait to ElementTrait.


208-214: JS event trigger test provides good coverage

Great implementation of a test that both triggers a JS event and verifies the resulting DOM changes (overlay becoming visible), providing comprehensive testing of the migrated functionality.


215-223: Confirmation dialog accept test is well structured

The test checks both the initial state (confirmation button exists but result doesn't), sets up the confirmation behavior, and then verifies the correct outcome after action.


224-232: Confirmation dialog decline test complements the accept test

Good implementation of the negative case to ensure both confirmation dialog responses work correctly. Together with the previous test, this provides complete coverage of the dialog interaction functionality.


233-237: Scroll functionality test is comprehensive

The test properly verifies both the scrolling action and the resulting element position, covering both parts of the functionality.

@@ -69,6 +69,14 @@ default:
DrevOps\BehatScreenshotExtension:
dir: '%paths.base%/.logs/screenshots'
purge: false # Change to 'true' (no quotes) to purge screenshots on each run.
on_failed: true
always_fullscreen: true
fullscreen_algorithm: resize # 'stitch' (only if GD ext available) or 'resize'
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Fix spacing in comment

There's a minor formatting issue with the comment spacing.

-      fullscreen_algorithm: resize # 'stitch' (only if GD ext available) or 'resize'
+      fullscreen_algorithm: resize  # 'stitch' (only if GD ext available) or 'resize'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fullscreen_algorithm: resize # 'stitch' (only if GD ext available) or 'resize'
fullscreen_algorithm: resize # 'stitch' (only if GD ext available) or 'resize'
🧰 Tools
🪛 YAMLlint (1.35.1)

[warning] 74-74: too few spaces before comment

(comments)

Comment on lines +656 to +661
#### Assert the element :selector should be at the top of the viewport

```gherkin
@Then the element :selector should be at the top of the viewport
```

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Viewport position assertion step documentation needs an example

The documentation for asserting element position in viewport is missing an example unlike other steps.

Add an example for consistency with other step documentation:

 #### Assert the element :selector should be at the top of the viewport

 ```gherkin
 @Then the element :selector should be at the top of the viewport

+Example:
+gherkin +Then the element "#header" should be at the top of the viewport +


<!-- This is an auto-generated comment by CodeRabbit -->

Comment on lines +590 to +609
#### Accept confirmation dialogs appearing on the page

```gherkin
@Given I accept all confirmation dialogs
```
Example:
```gherkin
Given I accept all confirmation dialogs
```

#### Do not accept confirmation dialogs appearing on the page

```gherkin
@Given I do not accept any confirmation dialogs
```
Example:
```gherkin
Given I do not accept any confirmation dialogs
```

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Documentation for confirmation dialog steps is well migrated

The steps for accepting and declining confirmation dialogs have been properly moved from JsTrait to ElementTrait, maintaining consistent documentation.

Add blank lines around the code blocks to improve formatting:

 #### Accept confirmation dialogs appearing on the page

+
 ```gherkin
 @Given I accept all confirmation dialogs

Example:
+

Given I accept all confirmation dialogs

Do not accept confirmation dialogs appearing on the page

@Given I do not accept any confirmation dialogs

Example:
+

Given I do not accept any confirmation dialogs

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

594-594: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)

---

596-596: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)

---

604-604: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)

---

606-606: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit -->

Comment on lines +610 to +619
#### Click on the element defined by the selector

```gherkin
@When I click on the element :selector
```
Example:
```gherkin
When I click on the element ".button"
```

Copy link

Choose a reason for hiding this commen 10000 t

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Element click step documentation properly relocated

The documentation for clicking elements has been appropriately moved to ElementTrait.

Add blank lines around the code blocks to improve formatting:

 #### Click on the element defined by the selector

+
 ```gherkin
 @When I click on the element :selector

Example:
+

When I click on the element ".button"

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

614-614: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)

---

616-616: Fenced code blocks should be surrounded by blank lines
null

(MD031, blanks-around-fences)

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit -->

Comment on lines +620 to +624
#### When I trigger the JS event :event on the element :selector

```gherkin
@When I trigger the JS event :event on the element :selector
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

JS event trigger step documentation needs an example

The documentation for triggering JS events is missing an example unlike other steps.

Add an example for consistency with other step documentation:

 #### When I trigger the JS event :event on the element :selector

 ```gherkin
 @When I trigger the JS event :event on the element :selector

+Example:
+gherkin +When I trigger the JS event "click" on the element "#my-button" +


<!-- This is an auto-generated comment by CodeRabbit -->

Comment on lines 166 to 177
/**
* Click on the element defined by the selector.
*
* @code
* When I click on the element ".button"
* @endcode
*
* @When I click on the element :selector
*
* @javascript
*/
public function elementClick(string $element): void {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Improve parameter naming consistency

The method signature uses $element as the parameter name, but the PHPDoc and step definition use $selector. Consider renaming the parameter for consistency.

- public function elementClick(string $element): void {
+ public function elementClick(string $selector): void {
    $element = $this
      ->getSession()
      ->getPage()
      ->find('css', $element);

    $element->click();
  }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 207 to 228
/**
* Scroll to an element with ID.
*
* @When I scroll to the element :selector
*/
public function elementScrollTo(string $selector): void {
$this->getSession()->executeScript("
var element = document.querySelector('" . $selector . "');
element.scrollIntoView( true );
");
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for element scrolling

Similar to the click method, this function does not verify that the element exists before attempting to scroll to it, which could lead to unexpected behavior.

  public function elementScrollTo(string $selector): void {
+    $page = $this->getSession()->getPage();
+    $element = $page->find('css', $selector);
+    
+    if (!$element) {
+      throw new \RuntimeException(sprintf('Cannot scroll to element "%s" as it was not found on the page', $selector));
+    }
+    
    $this->getSession()->executeScript("
      var element = document.querySelector('" . $selector . "');
      element.scrollIntoView( true );
    ");
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
8000
/**
* Scroll to an element with ID.
*
* @When I scroll to the element :selector
*/
public function elementScrollTo(string $selector): void {
$this->getSession()->executeScript("
var element = document.querySelector('" . $selector . "');
element.scrollIntoView( true );
");
}
/**
* Scroll to an element with ID.
*
* @When I scroll to the element :selector
*/
public function elementScrollTo(string $selector): void {
$page = $this->getSession()->getPage();
$element = $page->find('css', $selector);
if (!$element) {
throw new \RuntimeException(sprintf(
'Cannot scroll to element "%s" as it was not found on the page',
$selector
));
}
$this->getSession()->executeScript("
var element = document.querySelector('" . $selector . "');
element.scrollIntoView( true );
");
}

Comment on lines +113 to +130
/**
* Assert the element :selector should be at the top of the viewport.
*
* @Then the element :selector should be at the top of the viewport
*/
public function elementAssertElementAtTopOfViewport(string $selector): void {
$script = <<<JS
(function() {
var element = document.querySelector('{$selector}');
var rect = element.getBoundingClientRect();
return (rect.top >= 0 && rect.top <= window.innerHeight);
})();
JS;
$result = $this->getSession()->evaluateScript($script);
if (!$result) {
throw new \Exception(sprintf("Element with selector '%s' is not at the top of the viewport.", $selector));
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Improve viewport position check precision

The condition on line 123 checks if an element is anywhere within the viewport, not specifically at the top. Consider refining this to check for a smaller distance from the top if that's the intended behavior.

-            return (rect.top >= 0 && rect.top <= window.innerHeight);
+            return (rect.top >= 0 && rect.top <= 10); // 10px tolerance for "top of viewport"

Comment on lines 231 to 251
protected function elementExectuteJs(string $selector, string $script) {
$driver = $this->getSession()->getDriver();
$scriptWrapper = "return (function() {
{{SCRIPT}}
}());";
$script = str_replace('{{ELEMENT}}', sprintf("document.querySelector('%s')", $selector), $script);
$script = str_replace('{{SCRIPT}}', $script, $scriptWrapper);

return $driver->evaluateScript($script);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Fix method name typo "Exectute" → "Execute"

There's a typo in the method name elementExectuteJs - it should be elementExecuteJs.

- protected function elementExectuteJs(string $selector, string $script) {
+ protected function elementExecuteJs(string $selector, string $script) {

Don't forget to update the method call on line 200 as well:

- $result = $this->elementExectuteJs($selector, $script);
+ $result = $this->elementExecuteJs($selector, $script);

Copy link
codecov bot commented Apr 30, 2025

Codecov Report

Attention: Patch coverage is 89.74359% with 4 lines in your changes missing coverage. Please review.

Project coverage is 81.61%. Comparing base (9bcb95a) to head (2c49295).
Report is 2 commits behind head on 3.x.

Files with missing lines Patch % Lines
src/ElementTrait.php 89.74% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              3.x     #370      +/-   ##
==========================================
- Coverage   81.63%   81.61%   -0.03%     
==========================================
  Files          32       31       -1     
  Lines        1677     1675       -2     
==========================================
- Hits         1369     1367       -2     
  Misses        308      308              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@AlexSkrypnyk AlexSkrypnyk force-pushed the feature/remove-jstrait branch from d006af2 to 2c49295 Compare April 30, 2025 02:23
@AlexSkrypnyk AlexSkrypnyk merged commit fab5622 into 3.x Apr 30, 2025
4 checks passed
@AlexSkrypnyk AlexSkrypnyk deleted the feature/remove-jstrait branch April 30, 2025 02:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0