cypress-plugin-grep-boxes 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ name: Cypress Tests
2
+
3
+ on: push
4
+
5
+ jobs:
6
+ cypress-run:
7
+ runs-on: ubuntu-22.04
8
+ steps:
9
+ - name: Checkout
10
+ uses: actions/checkout@v4
11
+ # Install npm dependencies, cache them correctly
12
+ # and run all Cypress tests
13
+ - name: Cypress run
14
+ uses: cypress-io/github-action@v6
@@ -0,0 +1,43 @@
1
+ # Contributing
2
+
3
+ Thanks for being willing to contribute!
4
+
5
+ **Working on your first Pull Request?** You can learn more from [Your First Pull Request on GitHub](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork)
6
+
7
+ ## Project setup
8
+
9
+ 1. Fork and clone the repo
10
+ 2. Run `npm install` to install dependencies
11
+ 3. Create a branch for your PR with `git checkout -b pr/your-branch-name`
12
+
13
+ > Tip: Keep your `main` branch pointing at the original repository and make
14
+ > pull requests from branches on your fork. To do this, run:
15
+ >
16
+ > ```
17
+ > git remote add upstream https://github.com/dennisbergevin/cypress-plugin-grep-boxes
18
+ > git fetch upstream
19
+ > git branch --set-upstream-to=upstream/main main
20
+ > ```
21
+ >
22
+ > This will add the original repository as a "remote" called "upstream," Then
23
+ > fetch the git information from that remote, then set your local `main`
24
+ > branch to use the upstream main branch whenever you run `git pull`. Then you
25
+ > can make all of your pull request branches based on this `main` branch.
26
+ > Whenever you want to update your version of `main`, do a regular `git pull`.
27
+
28
+ ## Committing and Pushing changes
29
+
30
+ Please make sure to run tests in `open` mode to verify functionality before you commit your changes:
31
+
32
+ ```bash
33
+ npx cypress open
34
+ ```
35
+
36
+ Make sure to include any test changes (if they exist) in your commit.
37
+
38
+ ## Help needed
39
+
40
+ Please checkout the [the open issues](https://github.com/dennisbergevin/cypress-plugin-grep-boxes/issues)
41
+
42
+ Also, please watch the repo and respond to questions/bug reports/feature
43
+ requests! Thanks!
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024, Dennis Bergevin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ <h2 align=center>Cypress plugin grep-boxes</h2>
2
+ <p align="center">
3
+ </p>
4
+
5
+ <p align="center">
6
+ A companion Cypress plugin for <code>cy-grep</code> that allows user to run specific test(s) in <code>open</code> mode.
7
+ </p>
8
+
9
+ ![Cypress-plugin-grep-boxes](./assets/cypress-plugin-grep-boxes-demo.gif)
10
+
11
+ ## Features
12
+
13
+ - ✅ A new UI test selection within `cypress open` to filter and run only selected tests in a given spec
14
+
15
+ #### Table of Contents
16
+
17
+ - [Installation](#-installation)
18
+ - [Setup](#-setup)
19
+ - [Open mode](#-open-mode)
20
+ - [Contributions](#contributions)
21
+
22
+ ---
23
+
24
+ ## 📦 Installation
25
+
26
+ 1. Install the following packages:
27
+
28
+ ```sh
29
+ npm install --save-dev @bahmutov/cy-grep # Dependent package for the plugin
30
+ npm install --save-dev cypress-plugin-grep-boxes
31
+ ```
32
+
33
+ 2. In `cypress/support/e2e.js` (For E2E tests) and/or `cypress/support/component.js` (For Component tests),
34
+
35
+ ```js
36
+ import { greppedTestToggle, addGrepButtons } from 'cypress-plugin-grep-boxes';
37
+ import registerCypressGrep from '@bahmutov/cy-grep/src/support';
38
+
39
+ registerCypressGrep();
40
+
41
+ greppedTestToggle();
42
+ addGrepButtons();
43
+ ```
44
+
45
+ ---
46
+
47
+ ## 🦺 Setup
48
+
49
+ **Recommended**: Set two common environment variables tied to the `@bahmutov/cy-grep` package to enhance the experience utilizing the grep logic within the Cypress Test Runner UI using cypress open:
50
+
51
+ ```json
52
+ {
53
+ "env": {
54
+ "grepOmitFiltered": true,
55
+ "grepFilterSpecs": true
56
+ }
57
+ }
58
+ ```
59
+
60
+ > [!NOTE]
61
+ > More information on `grepOmitFiltered` and `grepFilterSpecs` can be read within the [README for `@bahmutov/cy-grep`](https://github.com/bahmutov/cy-grep?tab=readme-ov-file#pre-filter-specs-grepfilterspecs).
62
+
63
+ ## ✅ Open mode
64
+
65
+ Within each spec, you can select any given number of suite(s) or individual test(s) and click the filter toggle located on the reporter above:
66
+
67
+ ![Cypress grep-boxes within UI mode](./assets/grep-boxes-ui.png)
68
+
69
+ ## Contributions
70
+
71
+ Feel free to open a pull request or drop any feature request or bug in the [issues](https://github.com/dennisbergevin/cypress-plugin-grep-boxes/issues).
72
+
73
+ Please see more details in the [contributing doc](./CONTRIBUTING.md).
Binary file
@@ -0,0 +1,143 @@
1
+ /// <reference types="cypress" />
2
+
3
+ // Welcome to Cypress!
4
+ //
5
+ // This spec file contains a variety of sample tests
6
+ // for a todo list app that are designed to demonstrate
7
+ // the power of writing tests in Cypress.
8
+ //
9
+ // To learn more about how Cypress works and
10
+ // what makes it such an awesome testing tool,
11
+ // please read our getting started guide:
12
+ // https://on.cypress.io/introduction-to-cypress
13
+
14
+ describe('example to-do app', () => {
15
+ beforeEach(() => {
16
+ // Cypress starts out with a blank slate for each test
17
+ // so we must tell it to visit our website with the `cy.visit()` command.
18
+ // Since we want to visit the same URL at the start of all our tests,
19
+ // we include it in our beforeEach function so that it runs before each test
20
+ cy.visit('https://example.cypress.io/todo');
21
+ });
22
+
23
+ it('displays two todo items by default', () => {
24
+ // We use the `cy.get()` command to get all elements that match the selector.
25
+ // Then, we use `should` to assert that there are two matched items,
26
+ // which are the two default items.
27
+ cy.get('.todo-list li').should('have.length', 2);
28
+
29
+ // We can go even further and check that the default todos each contain
30
+ // the correct text. We use the `first` and `last` functions
31
+ // to get just the first and last matched elements individually,
32
+ // and then perform an assertion with `should`.
33
+ cy.get('.todo-list li').first().should('have.text', 'Pay electric bill');
34
+ cy.get('.todo-list li').last().should('have.text', 'Walk the dog');
35
+ });
36
+
37
+ it('can add new todo items', () => {
38
+ // We'll store our item text in a variable so we can reuse it
39
+ const newItem = 'Feed the cat';
40
+
41
+ // Let's get the input element and use the `type` command to
42
+ // input our new list item. After typing the content of our item,
43
+ // we need to type the enter key as well in order to submit the input.
44
+ // This input has a data-test attribute so we'll use that to select the
45
+ // element in accordance with best practices:
46
+ // https://on.cypress.io/selecting-elements
47
+ cy.get('[data-test=new-todo]').type(`${newItem}{enter}`);
48
+
49
+ // Now that we've typed our new item, let's check that it actually was added to the list.
50
+ // Since it's the newest item, it should exist as the last element in the list.
51
+ // In addition, with the two default items, we should have a total of 3 elements in the list.
52
+ // Since assertions yield the element that was asserted on,
53
+ // we can chain both of these assertions together into a single statement.
54
+ cy.get('.todo-list li')
55
+ .should('have.length', 3)
56
+ .last()
57
+ .should('have.text', newItem);
58
+ });
59
+
60
+ it('can check off an item as completed', () => {
61
+ // In addition to using the `get` command to get an element by selector,
62
+ // we can also use the `contains` command to get an element by its contents.
63
+ // However, this will yield the <label>, which is lowest-level element that contains the text.
64
+ // In order to check the item, we'll find the <input> element for this <label>
65
+ // by traversing up the dom to the parent element. From there, we can `find`
66
+ // the child checkbox <input> element and use the `check` command to check it.
67
+ cy.contains('Pay electric bill')
68
+ .parent()
69
+ .find('input[type=checkbox]')
70
+ .check();
71
+
72
+ // Now that we've checked the button, we can go ahead and make sure
73
+ // that the list element is now marked as completed.
74
+ // Again we'll use `contains` to find the <label> element and then use the `parents` command
75
+ // to traverse multiple levels up the dom until we find the corresponding <li> element.
76
+ // Once we get that element, we can assert that it has the completed class.
77
+ cy.contains('Pay electric bill')
78
+ .parents('li')
79
+ .should('have.class', 'completed');
80
+ });
81
+
82
+ context('with a checked task', () => {
83
+ beforeEach(() => {
84
+ // We'll take the command we used above to check off an element
85
+ // Since we want to perform multiple tests that start with checking
86
+ // one element, we put it in the beforeEach hook
87
+ // so that it runs at the start of every test.
88
+ cy.contains('Pay electric bill')
89
+ .parent()
90
+ .find('input[type=checkbox]')
91
+ .check();
92
+ });
93
+
94
+ it('can filter for uncompleted tasks', () => {
95
+ // We'll click on the "active" button in order to
96
+ // display only incomplete items
97
+ cy.contains('Active').click();
98
+
99
+ // After filtering, we can assert that there is only the one
100
+ // incomplete item in the list.
101
+ cy.get('.todo-list li')
102
+ .should('have.length', 1)
103
+ .first()
104
+ .should('have.text', 'Walk the dog');
105
+
106
+ // For good measure, let's also assert that the task we checked off
107
+ // does not exist on the page.
108
+ cy.contains('Pay electric bill').should('not.exist');
109
+ });
110
+
111
+ it('can filter for completed tasks', () => {
112
+ // We can perform similar steps as the test above to ensure
113
+ // that only completed tasks are shown
114
+ cy.contains('Completed').click();
115
+
116
+ cy.get('.todo-list li')
117
+ .should('have.length', 1)
118
+ .first()
119
+ .should('have.text', 'Pay electric bill');
120
+
121
+ cy.contains('Walk the dog').should('not.exist');
122
+ });
123
+
124
+ it('can delete all completed tasks', () => {
125
+ // First, let's click the "Clear completed" button
126
+ // `contains` is actually serving two purposes here.
127
+ // First, it's ensuring that the button exists within the dom.
128
+ // This button only appears when at least one task is checked
129
+ // so this command is implicitly verifying that it does exist.
130
+ // Second, it selects the button so we can click it.
131
+ cy.contains('Clear completed').click();
132
+
133
+ // Then we can make sure that there is only one element
134
+ // in the list and our element does not exist
135
+ cy.get('.todo-list li')
136
+ .should('have.length', 1)
137
+ .should('not.have.text', 'Pay electric bill');
138
+
139
+ // Finally, make sure that the clear button no longer exists.
140
+ cy.contains('Clear completed').should('not.exist');
141
+ });
142
+ });
143
+ });
@@ -0,0 +1,22 @@
1
+ /// <reference types="cypress" />
2
+
3
+ context('Window', () => {
4
+ beforeEach(() => {
5
+ cy.visit('https://example.cypress.io/commands/window');
6
+ });
7
+
8
+ it('cy.window() - get the global window object', () => {
9
+ // https://on.cypress.io/window
10
+ cy.window().should('have.property', 'top');
11
+ });
12
+
13
+ it('cy.document() - get the document object', () => {
14
+ // https://on.cypress.io/document
15
+ cy.document().should('have.property', 'charset').and('eq', 'UTF-8');
16
+ });
17
+
18
+ it('cy.title() - get the title', () => {
19
+ // https://on.cypress.io/title
20
+ cy.title().should('include', 'Kitchen Sink');
21
+ });
22
+ });
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "Using fixtures to represent data",
3
+ "email": "hello@cypress.io",
4
+ "body": "Fixtures are a great way to mock data for responses to routes"
5
+ }
@@ -0,0 +1,25 @@
1
+ // ***********************************************
2
+ // This example commands.js shows you how to
3
+ // create various custom commands and overwrite
4
+ // existing commands.
5
+ //
6
+ // For more comprehensive examples of custom
7
+ // commands please read more here:
8
+ // https://on.cypress.io/custom-commands
9
+ // ***********************************************
10
+ //
11
+ //
12
+ // -- This is a parent command --
13
+ // Cypress.Commands.add('login', (email, password) => { ... })
14
+ //
15
+ //
16
+ // -- This is a child command --
17
+ // Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
18
+ //
19
+ //
20
+ // -- This is a dual command --
21
+ // Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
22
+ //
23
+ //
24
+ // -- This will overwrite an existing command --
25
+ // Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
@@ -0,0 +1,26 @@
1
+ // ***********************************************************
2
+ // This example support/e2e.js is processed and
3
+ // loaded automatically before your test files.
4
+ //
5
+ // This is a great place to put global configuration and
6
+ // behavior that modifies Cypress.
7
+ //
8
+ // You can change the location of this file or turn off
9
+ // automatically serving support files with the
10
+ // 'supportFile' configuration option.
11
+ //
12
+ // You can read more here:
13
+ // https://on.cypress.io/configuration
14
+ // ***********************************************************
15
+
16
+ // Import commands.js using ES2015 syntax:
17
+ import './commands';
18
+ import { greppedTestToggle, addGrepButtons } from '../../index';
19
+ import registerCypressGrep from '@bahmutov/cy-grep/src/support';
20
+
21
+ registerCypressGrep();
22
+ greppedTestToggle();
23
+ addGrepButtons();
24
+
25
+ // Alternatively you can use CommonJS syntax:
26
+ // require('./commands')
@@ -0,0 +1,16 @@
1
+ const { defineConfig } = require('cypress');
2
+
3
+ module.exports = defineConfig({
4
+ env: {
5
+ grepOmitFiltered: true,
6
+ grepFilterSpecs: true,
7
+ },
8
+ e2e: {
9
+ setupNodeEvents(on, config) {
10
+ // implement node event listeners here
11
+ require('@bahmutov/cy-grep/src/plugin')(config);
12
+ // IMPORTANT: return the config object
13
+ return config;
14
+ },
15
+ },
16
+ });
package/index.js ADDED
@@ -0,0 +1,315 @@
1
+ import registerCypressGrep from '@bahmutov/cy-grep';
2
+ /**
3
+ * Adds a toggle to reporter to grep selected tests.
4
+ */
5
+
6
+ const tests = [];
7
+
8
+ export const greppedTestToggle = () => {
9
+ registerCypressGrep();
10
+ const hasStyles = window.top?.document.querySelector('#grepTestToggleStyle');
11
+ const hasToggleButton = window.top?.document.querySelector('#grepTestToggle');
12
+ const defaultStyles = `
13
+ .reporter header {
14
+ overflow: visible;
15
+ z-index: 2;
16
+ }
17
+ #grepTestToggleControls {
18
+ position: relative;
19
+ display: inline-block;
20
+ }
21
+ #grepTestToggle {
22
+ display: none;
23
+ }
24
+ #grepTestToggleControls label {
25
+ background-color: transparent;
26
+ padding-top: 5px;
27
+ }
28
+ #grepTestToggleControls #grepTestToggleTooltip {
29
+ visibility: hidden;
30
+ width: 150px;
31
+ background-color: #f3f4fa;
32
+ color: #1b1e2e;
33
+ text-align: center;
34
+ padding: 5px;
35
+ border-radius: 3px;
36
+ position: absolute;
37
+ z-index: 1;
38
+ top: 27px;
39
+ left: 0px;
40
+ height: 28px;
41
+ }
42
+ #grepTestToggleControls:hover #grepTestToggleTooltip {
43
+ visibility: visible;
44
+ }
45
+ #grepTestToggleButton #grepTestToggleLabel {
46
+ cursor: pointer;
47
+ }
48
+ #grepTestToggleTooltip::after {
49
+ content: " ";
50
+ position: absolute;
51
+ bottom: 100%; /* At the top of the tooltip */
52
+ right: 85%;
53
+ margin-left: -5px;
54
+ border-width: 5px;
55
+ border-style: solid;
56
+ border-color: transparent transparent #f3f4fa transparent;
57
+ }
58
+ .reporter:has(#grepTestToggle:checked) .command.command-name-request:has(.command-is-event) {
59
+ display:none
60
+ }
61
+ `;
62
+ const turnOngrepTestToggleIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#afb3c7" class="bi bi-collection-play-fill" viewBox="0 0 16 16">
63
+ <path d="M2.5 3.5a.5.5 0 0 1 0-1h11a.5.5 0 0 1 0 1zm2-2a.5.5 0 0 1 0-1h7a.5.5 0 0 1 0 1zM0 13a1.5 1.5 0 0 0 1.5 1.5h13A1.5 1.5 0 0 0 16 13V6a1.5 1.5 0 0 0-1.5-1.5h-13A1.5 1.5 0 0 0 0 6zm6.258-6.437a.5.5 0 0 1 .507.013l4 2.5a.5.5 0 0 1 0 .848l-4 2.5A.5.5 0 0 1 6 12V7a.5.5 0 0 1 .258-.437"/>
64
+ </svg>`;
65
+
66
+ const turnOffgrepTestToggleIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#afb3c7" class="bi bi-collection-play" viewBox="0 0 16 16">
67
+ <path d="M2 3a.5.5 0 0 0 .5.5h11a.5.5 0 0 0 0-1h-11A.5.5 0 0 0 2 3m2-2a.5.5 0 0 0 .5.5h7a.5.5 0 0 0 0-1h-7A.5.5 0 0 0 4 1m2.765 5.576A.5.5 0 0 0 6 7v5a.5.5 0 0 0 .765.424l4-2.5a.5.5 0 0 0 0-.848z"/>
68
+ <path d="M1.5 14.5A1.5 1.5 0 0 1 0 13V6a1.5 1.5 0 0 1 1.5-1.5h13A1.5 1.5 0 0 1 16 6v7a1.5 1.5 0 0 1-1.5 1.5zm13-1a.5.5 0 0 0 .5-.5V6a.5.5 0 0 0-.5-.5h-13A.5.5 0 0 0 1 6v7a.5.5 0 0 0 .5.5z"/>
69
+ </svg>`;
70
+
71
+ const turnOffgrepTestToggleDescription = 'Filter selected tests';
72
+ const turnOngrepTestToggleDescription = 'Unfilter selected tests';
73
+
74
+ // append styles
75
+ if (!hasStyles) {
76
+ const reporterEl = window.top?.document.querySelector('#unified-reporter');
77
+ const reporterStyleEl = document.createElement('style');
78
+ reporterStyleEl.setAttribute('id', 'grepTestToggleStyle');
79
+ reporterStyleEl.innerHTML = defaultStyles;
80
+ reporterEl?.appendChild(reporterStyleEl);
81
+ }
82
+
83
+ if (!hasToggleButton) {
84
+ const header = window.top?.document.querySelector(
85
+ '#unified-reporter header'
86
+ );
87
+ const headerToggleDiv = document.createElement('div');
88
+ const headerToggleSpan = document.createElement('span');
89
+ const headerToggleTooltip = document.createElement('span');
90
+ const headerToggleButton = document.createElement('button');
91
+ const headerToggleInput = document.createElement('input');
92
+ const headerToggleLabel = document.createElement('label');
93
+
94
+ headerToggleInput.setAttribute('type', 'checkbox');
95
+
96
+ headerToggleInput.setAttribute('id', 'grepTestToggle');
97
+ headerToggleLabel.setAttribute('for', 'grepTestToggle');
98
+ headerToggleLabel.setAttribute('id', 'grepTestToggleLabel');
99
+ headerToggleLabel.innerHTML = turnOffgrepTestToggleIcon;
100
+
101
+ headerToggleDiv.setAttribute('class', 'controls');
102
+ headerToggleDiv.setAttribute('id', 'grepTestToggleControls');
103
+ headerToggleTooltip.setAttribute('id', 'grepTestToggleTooltip');
104
+ headerToggleTooltip.innerText = turnOffgrepTestToggleDescription;
105
+ headerToggleButton.setAttribute(
106
+ 'aria-label',
107
+ turnOffgrepTestToggleDescription
108
+ );
109
+ headerToggleButton.setAttribute('id', 'grepTestToggleButton');
110
+
111
+ header?.appendChild(headerToggleDiv);
112
+ headerToggleDiv?.appendChild(headerToggleSpan);
113
+ headerToggleDiv?.appendChild(headerToggleTooltip);
114
+ headerToggleSpan?.appendChild(headerToggleButton);
115
+ headerToggleButton?.appendChild(headerToggleInput);
116
+ headerToggleButton?.appendChild(headerToggleLabel);
117
+ }
118
+
119
+ const grepTestToggleElement =
120
+ window.top?.document.querySelector('#grepTestToggle');
121
+ const grepTestToggleLabelElement = window.top?.document.querySelector(
122
+ '[for=grepTestToggle]'
123
+ );
124
+ const grepTestToggleTooltipElement = window.top?.document.querySelector(
125
+ '#grepTestToggleTooltip'
126
+ );
127
+
128
+ grepTestToggleElement?.addEventListener('change', (e) => {
129
+ const stopBtn = window.top?.document.querySelector('.reporter .stop');
130
+
131
+ if (e.target.checked) {
132
+ if (stopBtn) {
133
+ stopBtn.click();
134
+ }
135
+ // store all checked checkbox values then send to grep in accepted format
136
+ const tests = [
137
+ ...window.top?.document.querySelectorAll('.grep-test-checkbox:checked'),
138
+ ].map((e) => e.value);
139
+ // store all non-checked checkbox values
140
+ const uncheckedTests = [
141
+ ...window.top?.document.querySelectorAll(
142
+ '.grep-test-checkbox:not(:checked)'
143
+ ),
144
+ ].map((e) => e.value);
145
+
146
+ tests.forEach((t) => {
147
+ // if a checked test title begins with the grep inverted '-' symbol, remove the '-'
148
+ if (t[0] === '-') {
149
+ tests.push(t.slice(1));
150
+ tests.splice(
151
+ tests.findIndex((e) => e === t),
152
+ 1
153
+ );
154
+ }
155
+ // if a non-checked test's title includes a checked test's title, invert grep for unchecked title
156
+ uncheckedTests.forEach((u) => {
157
+ if (u.includes(t)) {
158
+ tests.push(`-${u}`);
159
+ }
160
+ });
161
+ });
162
+
163
+ Cypress.grep(tests.join(';'));
164
+
165
+ // when checked, grep only selected tests in spec
166
+ grepTestToggleLabelElement.innerHTML = turnOngrepTestToggleIcon;
167
+ grepTestToggleTooltipElement.innerHTML = turnOngrepTestToggleDescription;
168
+ } else {
169
+ if (stopBtn) {
170
+ stopBtn.click();
171
+ }
172
+ // when unchecked, ungrep and show all tests in spec
173
+ Cypress.grep();
174
+ grepTestToggleLabelElement.innerHTML = turnOffgrepTestToggleIcon;
175
+ grepTestToggleTooltipElement.innerHTML = turnOffgrepTestToggleDescription;
176
+ }
177
+ });
178
+ };
179
+
180
+ /**
181
+ * Adds a checkbox for each suite and test for run selection.
182
+ */
183
+
184
+ export const addGrepButtons = () => {
185
+ const hasStyles = window.top?.document.querySelector('#grepButtonsStyle');
186
+
187
+ const grepTestsBtnClass = 'grep-tests-btn';
188
+
189
+ const defaultStyles = `
190
+ .grep-tests-btn {
191
+ background: none;
192
+ color: inherit;
193
+ padding: 0 20px;
194
+ verticalAlign: baseline;
195
+ }
196
+
197
+ .grep-test-checkbox {
198
+ appearance: inherit;
199
+ cursor: pointer;
200
+ }
201
+ `;
202
+
203
+ if (!hasStyles) {
204
+ const runnablesEl = window.top?.document.querySelector('.runnables');
205
+ const runnablesStyleEl = window.top?.document.createElement('style');
206
+ runnablesStyleEl.setAttribute('id', 'grepButtonsStyle');
207
+ runnablesStyleEl.innerHTML = defaultStyles;
208
+ runnablesEl?.appendChild(runnablesStyleEl);
209
+ }
210
+ const testsAndSuites = window.top?.document.querySelectorAll(
211
+ '.test.runnable, .suite.runnable'
212
+ );
213
+ [...testsAndSuites].forEach((t) => {
214
+ const header = t.querySelector('.collapsible-header');
215
+ const title = header.querySelector('.runnable-title');
216
+ const testName = title.innerText.split('\n')[0];
217
+
218
+ // Don't add the button if it already exists
219
+ if (header.querySelectorAll(`.${grepTestsBtnClass}`).length) {
220
+ return;
221
+ }
222
+
223
+ const grepTestsBtn = window.top?.document.createElement('button');
224
+ grepTestsBtn.className = grepTestsBtnClass;
225
+ grepTestsBtn.style.background = 'none';
226
+ grepTestsBtn.style.color = 'inherit';
227
+ grepTestsBtn.style.padding = '0 20px';
228
+ grepTestsBtn.style.verticalAlign = 'baseline';
229
+ grepTestsBtn.setAttribute(
230
+ 'aria-label',
231
+ 'Checkbox to select suite/test for filtering'
232
+ );
233
+
234
+ // Add checkbox
235
+ const checkbox = window.top?.document.createElement('input');
236
+ checkbox.className = 'grep-test-checkbox';
237
+ checkbox.type = 'checkbox';
238
+ checkbox.value = testName;
239
+ if (tests.includes(checkbox.value)) {
240
+ checkbox.checked = true;
241
+ }
242
+
243
+ grepTestsBtn.appendChild(checkbox);
244
+ header.appendChild(grepTestsBtn);
245
+
246
+ // Push checked tests to an array for temporary storage
247
+ // This is for when a suite collapses in UI and removes a given test runnable
248
+ // When the collapsible expands, any previously checked test will remain checked
249
+ checkbox?.addEventListener('change', (e) => {
250
+ if (e.target.checked) {
251
+ tests.push(checkbox.value);
252
+ } else {
253
+ tests.splice(
254
+ tests.findIndex((e) => e === checkbox.value),
255
+ 1
256
+ );
257
+ }
258
+ });
259
+
260
+ // To prevent a checkbox from expanding a runnable, click the collapsible
261
+ grepTestsBtn?.addEventListener('change', (e) => {
262
+ if (e.target.checked) {
263
+ header.click();
264
+ }
265
+ });
266
+ });
267
+ };
268
+
269
+ // Wrapping logic within isInteractive check
270
+ // This targets cypress open mode where user can switch specs
271
+ if (Cypress.config('isInteractive')) {
272
+ Cypress.on('window:unload', () => {
273
+ // Store the current Cypress test runner url
274
+ // This is to check against any spec change in test runner while the grep filter is activated
275
+ // If a user does switch spec while filter is active, the filter will be reset
276
+ const sidebarSpecLinkPage = window.top?.document.querySelector(
277
+ '[data-cy="sidebar-link-specs-page"]'
278
+ );
279
+ const grepTestToggleElement =
280
+ window.top?.document.querySelector('#grepTestToggle');
281
+
282
+ if (
283
+ window.top?.document.URL !=
284
+ sidebarSpecLinkPage.getAttribute('data-url') &&
285
+ grepTestToggleElement.checked
286
+ ) {
287
+ grepTestToggleElement.click();
288
+ }
289
+
290
+ sidebarSpecLinkPage.setAttribute('data-url', window.top?.document.URL);
291
+ });
292
+ }
293
+
294
+ Cypress.on('test:before:run', () => {
295
+ if (
296
+ // if the grep test toggle is checked, do not show checkboxes on each runnable
297
+ window.top?.document.querySelectorAll('#grepTestToggle:checked').length ===
298
+ 0
299
+ ) {
300
+ addGrepButtons();
301
+ }
302
+ });
303
+
304
+ // To account for when the collapsible runnables are removed, add back grep buttons
305
+ if (
306
+ // if the grep test toggle is checked, do not show checkboxes on each runnable
307
+ window.top?.document.querySelectorAll('#grepTestToggle:checked').length === 0
308
+ ) {
309
+ window.top?.document.addEventListener('click', () => {
310
+ addGrepButtons();
311
+ });
312
+ window.top?.document.addEventListener('keypress', () => {
313
+ addGrepButtons();
314
+ });
315
+ }
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "cypress-plugin-grep-boxes",
3
+ "version": "1.0.0",
4
+ "description": "Cypress plugin that allows user to run specific tests in open mode.",
5
+ "main": "./index.js",
6
+ "keywords": [
7
+ "cypress",
8
+ "testing",
9
+ "cypress-plugin"
10
+ ],
11
+ "devDependencies": {
12
+ "@bahmutov/cy-grep": "^1.9.17",
13
+ "cypress": "^13.10.0"
14
+ },
15
+ "publishConfig": {
16
+ "registry": "https://registry.npmjs.org/"
17
+ },
18
+ "author": "Dennis Bergevin",
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/dennisbergevin/cypress-plugin-grep-boxes.git"
23
+ },
24
+ "bugs": {
25
+ "url": "https://github.com/dennisbergevin/cypress-plugin-grep-boxes/issues"
26
+ },
27
+ "homepage": "https://github.com/dennisbergevin/cypress-plugin-grep-boxes#readme"
28
+ }