rails-jsdom 0.2.1 → 0.3.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e994edad2df89164bf6c258b89b869184d5d724bdd71bad8b1cf075ded08b566
4
- data.tar.gz: 78b8bf908d342b08dafe80de1423b9474fac4f6b63c8acd507c4f0371210eba2
3
+ metadata.gz: 1d10f2ae96f0c6db3cec97724c5439407477250f5302ced18882a4f95b9dc031
4
+ data.tar.gz: a83654ff8968e706d90e55c99f724cd9b62bcb7fd685e9a35f5022b00de5d93b
5
5
  SHA512:
6
- metadata.gz: 9f3317df6c4401589b032c5aa07e7d5ca29a7ce82033df5722645f71c70f31543457c6ff020d267bbdc5dc021a3f5953fe5684ef3e1276bbe9108a8fce955839
7
- data.tar.gz: f9b5a3bb28b8f161ad5069591d56ad83d0930562a174453b1cef568e5fa9276eea40b48d2e7d8b968ed72573ba4c59bf8306b18e254ba34881bfc2b87168948d
6
+ metadata.gz: d4525c006c90dddb5ada07648c32187a30427f28bfb092a27dbf3545d96368e62a38619932b2c12603c47def6c9c23af4ae583670dfa370e566d5356faabf100
7
+ data.tar.gz: 3d04280f3ce16f09a51ee99199ef9ccea53f2109f8dcd456eac6fb8325557cb0f52d9a1c3763fc417a01e4264739167833f2bf9f03f5cfbb010a443ba1c2911b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 (2026-11-28)
4
+
5
+ ### Added
6
+
7
+ - Apps that bundle their JavaScript (esbuild, Bun, Vite, webpack) instead of using importmap. `RailsJsdom.entry` names the app's entry module, which runs on every page in place of the importmap's `application` module; bare `import()` calls in it are bundled from `node_modules`.
8
+ - `RailsJsdom.register_controllers = false` leaves Stimulus controller registration to the app's own JavaScript, so a controller its entry registers does not connect twice. Errors from every Stimulus application on the page still fail the action.
9
+ - `RailsJsdom.esbuild_config` names a module of the app that receives the esbuild build options and returns them, for plugins, loaders and defines that bundler-specific syntax needs.
10
+ - An app without importmap configured gets no pins instead of an error.
11
+ - `RailsJsdom.hidden_selectors` names selectors the app's stylesheets always hide, such as a `.hide` utility class. Assertions, finders and visible text treat matching elements, and their descendants, as hidden.
12
+ - `header(name, value)` sends a header, such as a phone's `User-Agent`, with every request Rails receives from the test from then on, including the requests its pages make. A request that sets the header itself keeps its own value.
13
+
14
+ ### Changed
15
+
16
+ - An action whose locator matches several elements acts on the one that is visible and enabled, as Capybara does, instead of failing as ambiguous. A disabled search box beside the live one, or a hidden copy of a button, no longer gets in the way. When no match is visible and enabled, the action behaves as before: a hidden file field is still attached to, and a disabled button still fails with "is disabled".
17
+ - An action whose every match is hidden fails with "unable to find … every match is hidden", as a click on something the user cannot see fails in a browser. A hidden file field is the exception: `attach_file` still attaches to it.
18
+ - `within` scopes to the one visible match when hidden elements share its selector, as Capybara does, instead of failing as ambiguous. A selector that matches only hidden elements still scopes to the one it matches.
19
+
20
+ ### Fixed
21
+
22
+ - Opening a cable connection closes the response body of the request it makes to the app, so the Rails executor completes. It was left running on the test's thread until the next request, so a test that followed without making one ran inside it: jobs a commit enqueued were held back, and `Current` kept the earlier test's values.
23
+ - A `<dialog>`'s `returnValue` starts as `""` and holds the value it was closed with as a string, as in browsers. jsdom left it undefined, so code that checks for an empty return value to tell a dismissal from a choice saw a choice.
24
+ - The page's visible text includes elements a script appends to the root element after `<body>`, which browsers render, such as a fragment Turbo appends when it renders a stream message. Only `<body>` was read before. `<head>` is still left out.
25
+ - Escape cancels the topmost modal `<dialog>`, including one inside a shadow root such as a Web Awesome dialog's: it fires a cancelable `cancel` event and closes the dialog unless that event is prevented, as browsers do. jsdom has no close watcher, so Escape left modals open.
26
+ - A script that navigates with `location.href =`, `location.assign`, `location.replace` or `location.reload` loads the page Rails answers with, as a link would. jsdom reported "Not implemented: navigation to another Document", which failed the action; Turbo uses `location.href` for the full reload it does when a visit's tracked assets change. Fragment and non-HTTP locations stay in the document.
27
+ - `fill_in` and typed keys set a field's value through the browser's own `value` setter, so a page that installs its own setter on the field to track changes, as React does for controlled inputs, sees the change and runs its `onChange`. React ignored values set by `fill_in` before.
28
+ - `contentEditable` reflects the `contenteditable` attribute (`"true"`, `"false"`, `"plaintext-only"` or `"inherit"`), and setting it makes an element editable or not. jsdom left it undefined, so libraries that check it before binding to an editor, such as Tribute on a Trix editor, threw.
29
+ - A label's `for` names every field with that id, as in Capybara, so a field still matches its label when a hidden input earlier in the page shares the id, as Rails form builders sometimes render. jsdom's `label.control` resolved to the hidden input, which is not labelable, so the field was not found.
30
+ - Inline event handler attributes such as `onchange` keep working on elements adopted from a parsed document, which is how Turbo renders the pages it visits. jsdom dropped them, so after the first Turbo visit an inline handler never ran.
31
+ - Enter in a field submits through the first submit button its form owns. A button inside the form that belongs to another form through its `form` attribute is skipped, as browsers do, instead of being clicked.
32
+ - Requests a page makes to its own origin (fetch, XMLHttpRequest, form submissions, Turbo visits) send the page's URL, without its fragment, as `Referer`, as browsers do. `redirect_back` and `request.referer` saw nothing before. A request that sets its own `Referer` keeps it.
33
+ - A submit button's `formMethod` property reflects its `formmethod` attribute, as browsers do. jsdom left it undefined, so turbo-rails sent a `formmethod="delete"` button's form as the form's own method instead.
34
+ - A field named by two labels, such as a visible label and a hidden copy for another layout, is one match for `fill_in` and the other field helpers instead of an ambiguous two.
35
+
3
36
  ## 0.2.1 (2026-11-14)
4
37
 
5
38
  ### Fixed
data/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # rails-jsdom
2
2
 
3
- Browserless interaction tests for Rails apps built with Stimulus, Turbo and importmap.
3
+ Browserless interaction tests for Rails apps built with Stimulus, Turbo and importmap, or with a JavaScript bundler.
4
4
 
5
5
  `rails-jsdom` lets you write tests that read like system tests — `visit`, `click_on`, `fill_in`, `assert_selector`, `assert_text` — without Capybara, a test server or a browser. Your real pages render through Rails, your real Stimulus controllers and Turbo run in [jsdom](https://github.com/jsdom/jsdom), and every request the page makes is answered by Rails in the same test process. Tests run deterministically, fail on JavaScript errors, and in [37signals' open-source apps](#results-on-37signals-open-source-apps) ran 1.8x to 16.5x faster than the same tests as system tests.
6
6
 
@@ -27,6 +27,8 @@ end
27
27
  - [Trade-offs compared with system tests](#trade-offs-compared-with-system-tests)
28
28
  - [Requirements](#requirements)
29
29
  - [Installation](#installation)
30
+ - [Apps that bundle JavaScript (esbuild, Bun, Vite, webpack)](#apps-that-bundle-javascript-esbuild-bun-vite-webpack)
31
+ - [Hiding by class](#hiding-by-class)
30
32
  - [Writing tests](#writing-tests)
31
33
  - [API](#api)
32
34
  - [Action Cable and Turbo Stream broadcasts](#action-cable-and-turbo-stream-broadcasts)
@@ -40,7 +42,7 @@ end
40
42
  ## How it works
41
43
 
42
44
  1. Each test worker starts one persistent Node process running jsdom.
43
- 2. Node bundles your importmap's `application` module and your Stimulus controllers once with [esbuild](https://esbuild.github.io), from your app's own importmap, so the versions under test are the ones your app ships.
45
+ 2. Node bundles your importmap's `application` module and your Stimulus controllers once with [esbuild](https://esbuild.github.io), from your app's own importmap, so the versions under test are the ones your app ships. An app that bundles its JavaScript names its [entry module](#apps-that-bundle-javascript-esbuild-bun-vite-webpack) instead.
44
46
  3. `visit` makes a real Rails request and loads the response into a jsdom window. Your `application` module runs, Turbo and Stimulus boot, and controllers connect in the same order as with `stimulus-loading` in a browser.
45
47
  4. Every `fetch` and `XMLHttpRequest` the page makes, including Turbo visits, form submissions, frames and direct uploads, is answered by Rails in the same process, with the test's session.
46
48
  5. After every action, the page **settles**: timers run on a virtual clock, Action Cable messages are delivered, and pending requests finish. Assertions then read the live DOM, so there is nothing to wait for.
@@ -89,8 +91,8 @@ jsdom runs the DOM and JavaScript but does not lay out or paint pages. Keep a fe
89
91
  ## Requirements
90
92
 
91
93
  - Ruby 3.3, 3.4 or 4.0
92
- - Rails 8.1 with `importmap-rails`, `propshaft`, `turbo-rails` and `stimulus-rails`
93
- - Stimulus controllers under `app/javascript/controllers`, named `*_controller.js`
94
+ - Rails 8.1 with `turbo-rails` and `stimulus-rails`, and either `importmap-rails` and `propshaft` or a JavaScript bundler (see [Apps that bundle JavaScript](#apps-that-bundle-javascript-esbuild-bun-vite-webpack))
95
+ - With importmap, Stimulus controllers under `app/javascript/controllers`, named `*_controller.js`
94
96
  - Node.js 22.22.2+, 24.15+ or 26+, the supported LTS lines that jsdom 31 runs on
95
97
 
96
98
  CI also runs the suite against edge Rails.
@@ -116,6 +118,71 @@ It also protects you from compromised npm releases:
116
118
  - `.npmrc` gets `min-release-age=7`, so npm skips versions published in the last 7 days. This needs npm 11.10 or later, and the generator warns if yours is older.
117
119
  - Commit `package-lock.json` and use `npm ci` in CI, so new versions only arrive when someone updates and commits them.
118
120
 
121
+ ## Apps that bundle JavaScript (esbuild, Bun, Vite, webpack)
122
+
123
+ An app that bundles its JavaScript instead of using importmap tells rails-jsdom where its entry module is, in `test/test_helper.rb` after `require "rails_jsdom"`:
124
+
125
+ ```ruby
126
+ RailsJsdom.entry = "app/javascript/application.js"
127
+ RailsJsdom.register_controllers = false
128
+ RailsJsdom.esbuild_config = "test/rails_jsdom.esbuild.mjs"
129
+ ```
130
+
131
+ - **`RailsJsdom.entry`** is the module your bundler starts from, relative to the app's root. It runs on every page, as the importmap's `application` module would. Bare imports, including `import()` of a package, are bundled from `node_modules`. An `import()` of a URL is left to load when it runs, and fails, since pages have no network.
132
+ - **`RailsJsdom.register_controllers = false`** leaves controller registration to your entry, which usually registers them itself (a `controllers/index.js` manifest, `import.meta.glob` or `require.context`). Without it, rails-jsdom also registers each `app/javascript/controllers/*_controller.js` on `window.Stimulus`, and a controller would connect twice. Errors from every Stimulus application on the page still fail the action that caused them, unless your app gives its application its own `handleError`.
133
+ - **`RailsJsdom.esbuild_config`** is optional: a module whose default export receives the esbuild build options and returns them, or a promise of them. rails-jsdom bundles with esbuild whichever bundler the app uses, so syntax that only your bundler understands needs an esbuild plugin, loader or define here. `options.plugins` holds rails-jsdom's own plugin; put yours first to resolve a specifier before it does.
134
+
135
+ For a Vite app, this config expands eager `import.meta.glob` calls, loads `?raw` imports as text, and compiles JSX in `.js` files:
136
+
137
+ ```js
138
+ import fs from "node:fs"
139
+ import path from "node:path"
140
+
141
+ const GLOB = /import\.meta\.glob\(\s*(["'])(.+?)\1\s*,\s*\{\s*eager:\s*true\s*\}\s*\)/g
142
+
143
+ function expandGlobs(file, source) {
144
+ const imports = []
145
+ const code = source.replace(GLOB, (_call, _quote, pattern) => {
146
+ const matches = fs.globSync(pattern, { cwd: path.dirname(file) }).sort().map(match => `./${match}`)
147
+ const entries = matches.map(match => {
148
+ imports.push(`import * as glob${imports.length} from ${JSON.stringify(match)}`)
149
+ return `${JSON.stringify(match)}: glob${imports.length - 1}`
150
+ })
151
+ return `{ ${entries.join(", ")} }`
152
+ })
153
+ return `${imports.join("\n")}\n${code}`
154
+ }
155
+
156
+ const vite = {
157
+ name: "vite",
158
+ setup(build) {
159
+ build.onLoad({ filter: /app\/javascript\/.*\.jsx?$/ }, args => {
160
+ const source = fs.readFileSync(args.path, "utf8")
161
+ return { contents: expandGlobs(args.path, source), loader: "jsx" }
162
+ })
163
+ build.onResolve({ filter: /\?raw$/ }, args => ({ path: path.resolve(args.resolveDir, args.path.slice(0, -4)), namespace: "raw" }))
164
+ build.onLoad({ filter: /.*/, namespace: "raw" }, args => ({ contents: fs.readFileSync(args.path, "utf8"), loader: "text" }))
165
+ }
166
+ }
167
+
168
+ export default options => ({
169
+ ...options,
170
+ jsx: "automatic",
171
+ define: { "process.env.NODE_ENV": "\"production\"" },
172
+ plugins: [vite, ...options.plugins]
173
+ })
174
+ ```
175
+
176
+ ## Hiding by class
177
+
178
+ Assertions and finders skip what the page hides with the `hidden` attribute, an inline `display: none`, a closed `<dialog>` or `<details>`, and elements such as `<template>`. rails-jsdom does not apply stylesheets, so an element that the app's CSS hides, such as one with a `.hide` utility class, counts as visible. Name those selectors in `test/test_helper.rb` after `require "rails_jsdom"`:
179
+
180
+ ```ruby
181
+ RailsJsdom.hidden_selectors = [ ".hide", "wa-dialog:not([open])" ]
182
+ ```
183
+
184
+ An element matching one of them is hidden, with everything inside it. Only list selectors that always hide what they match.
185
+
119
186
  ## Writing tests
120
187
 
121
188
  Inherit from `RailsJsdom::TestCase`, which is an `ActionDispatch::IntegrationTest`, so fixtures, `sign_in` helpers that post to your session controller, `perform_enqueued_jobs` and all Rails assertions work as usual.
@@ -201,6 +268,7 @@ The full API reference is at **[jakehow.github.io/rails-jsdom](https://jakehow.g
201
268
  | [`stub_fetch`](https://jakehow.github.io/rails-jsdom/RailsJsdom/TestHelper.html#method-i-stub_fetch) | Answers a page request without Rails |
202
269
  | [`stub_layout`](https://jakehow.github.io/rails-jsdom/RailsJsdom/TestHelper.html#method-i-stub_layout) | Gives elements matching a selector, and ranges inside them, a box instead of 0x0, for a test whose page waits for a real measurement |
203
270
  | [`page_text`](https://jakehow.github.io/rails-jsdom/RailsJsdom/TestHelper.html#method-i-page_text) | The visible text of the page or the current `within` scope |
271
+ | [`header`](https://jakehow.github.io/rails-jsdom/RailsJsdom/TestHelper.html#method-i-header) | Sends a header, such as a phone's `User-Agent`, with every request Rails receives from then on: visits and the requests pages make. A request that sets the header itself keeps its own value. Like rack_test's `page.driver.header` |
204
272
 
205
273
  `assert_dom`, `assert_select` and `css_select` work as in any Rails test and read the live page.
206
274
 
@@ -253,7 +321,7 @@ CI needs Node and your app's npm packages before the tests run:
253
321
 
254
322
  See [what you lose](#trade-offs-compared-with-system-tests). In addition:
255
323
 
256
- - jsdom lacks some browser APIs, so the runtime stubs the common ones to keep controllers working: `matchMedia` never matches, `IntersectionObserver` and `ResizeObserver` never report, scrolling does nothing, stylesheets and images fire `load` without being fetched, and the clipboard, Fullscreen API, `DataTransfer` and form-associated custom elements are provided. The page behaves as a desktop browser without touch. A page that needs another missing API needs a small stub in your controller or test.
324
+ - jsdom lacks some browser APIs, so the runtime stubs the common ones to keep controllers working: `matchMedia` never matches, `IntersectionObserver` and `ResizeObserver` never report, scrolling does nothing, stylesheets and images fire `load` without being fetched, and the clipboard, Fullscreen API, `DataTransfer`, a submit button's `formMethod`, `contentEditable` and form-associated custom elements are provided. The page behaves as a desktop browser without touch. A page that needs another missing API needs a small stub in your controller or test.
257
325
  - On a page loaded with `mount_html`, a link or form that leads to a full app page fails. Start such tests from a real page with `visit`.
258
326
  - Stimulus outlets are not tested yet.
259
327
 
@@ -112,7 +112,8 @@ module RailsJsdom
112
112
 
113
113
  def open(url, protocols, cookie)
114
114
  @protocol = (protocols & ActionCable::INTERNAL[:protocols]).first.to_s
115
- status, = Rails.application.call(self.class.env(url, protocols, cookie).merge(ENV_KEY => self))
115
+ status, _headers, body = Rails.application.call(self.class.env(url, protocols, cookie).merge(ENV_KEY => self))
116
+ body.close
116
117
  status == -1 ? { protocol: @protocol } : { error: "the cable endpoint answered #{status}" }
117
118
  end
118
119
 
@@ -5,6 +5,7 @@ const path = require("node:path")
5
5
  const readline = require("node:readline")
6
6
  const vm = require("node:vm")
7
7
  const { createRequire } = require("node:module")
8
+ const { pathToFileURL } = require("node:url")
8
9
 
9
10
  const STUB_NAMESPACE = "rails-jsdom-stub"
10
11
  const STUB_SOURCE = "module.exports = Object.create(new Proxy({}, { get: (target, key) => typeof key === 'symbol' || key === 'then' || key === '__esModule' ? undefined : () => {} }))"
@@ -28,9 +29,11 @@ const SETTLE_LIMIT = 10000
28
29
  const MEASUREMENT_LIMIT = 10000
29
30
  const LAYOUT_LOOP = `RailsJsdom: the page measured element positions ${MEASUREMENT_LIMIT} times without its event loop moving on. jsdom has no layout, so every element and range measures 0x0 at 0,0, and code that waits for a real measurement, such as positioning a menu or popover at the caret, never gets one and repeats forever. If the test does not depend on where things are, give the elements involved a box with stub_layout in that test; otherwise test this behaviour in a system test.`
30
31
  const LOADABLE = "link[rel~=stylesheet], img[src]:not([src=\"\"])"
32
+ const URL_SPECIFIER = /^[a-z][a-z0-9+.-]*:/i
31
33
 
32
34
  const replies = new Map()
33
35
  const fetchStubs = new Map()
36
+ const openModals = new WeakMap()
34
37
  const pending = new Set()
35
38
  const errors = []
36
39
  const owners = new WeakMap()
@@ -44,6 +47,7 @@ let inbox = []
44
47
  let config = null
45
48
  let jsdom = null
46
49
  let wrappers = null
50
+ let urls = null
47
51
  let bundle = null
48
52
  let page = null
49
53
  const sessions = new Map()
@@ -174,8 +178,9 @@ async function setup(message) {
174
178
  const appRequire = createRequire(path.join(config.root, "package.json"))
175
179
  jsdom = appRequire("jsdom")
176
180
  wrappers = appRequire("jsdom/lib/generated/idl/utils.js")
181
+ urls = createRequire(appRequire.resolve("jsdom"))("whatwg-url")
177
182
  const esbuild = appRequire("esbuild")
178
- const result = await esbuild.build({
183
+ const result = await esbuild.build(await configureBuild({
179
184
  stdin: { contents: entrySource(), resolveDir: config.root, sourcefile: "rails-jsdom-entry.js", loader: "js" },
180
185
  bundle: true,
181
186
  write: false,
@@ -183,11 +188,17 @@ async function setup(message) {
183
188
  globalName: "RailsJsdomBundle",
184
189
  logLevel: "silent",
185
190
  plugins: [importmapPlugin()]
186
- })
191
+ }))
187
192
  bundle = new vm.Script(result.outputFiles[0].text, { filename: "rails-jsdom-bundle.js" })
188
193
  return {}
189
194
  }
190
195
 
196
+ async function configureBuild(options) {
197
+ if (!config.esbuild) return options
198
+ const { default: configure } = await import(pathToFileURL(config.esbuild).href)
199
+ return await configure(options)
200
+ }
201
+
191
202
  function controllerFiles(directory, prefix) {
192
203
  return fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap(entry => {
193
204
  if (entry.isDirectory()) return controllerFiles(path.join(directory, entry.name), `${prefix}${entry.name}/`)
@@ -200,16 +211,21 @@ function identifierFor(relative) {
200
211
  }
201
212
 
202
213
  function entrySource() {
203
- const files = controllerFiles(config.controllers, "")
214
+ const files = config.controllers ? controllerFiles(config.controllers, "") : []
204
215
  return [
205
216
  "import \"@hotwired/turbo-rails\"",
206
217
  "export { Application } from \"@hotwired/stimulus\"",
207
218
  ...files.map(([, file], index) => `import controller${index} from ${JSON.stringify(file)}`),
208
219
  `export const controllers = { ${files.map(([relative], index) => `${JSON.stringify(identifierFor(relative))}: controller${index}`).join(", ")} }`,
209
- ...(config.modules.application ? ["import \"application\""] : [])
220
+ ...applicationImport()
210
221
  ].join("\n")
211
222
  }
212
223
 
224
+ function applicationImport() {
225
+ if (config.entry) return [`import ${JSON.stringify(config.entry)}`]
226
+ return config.modules.application ? ["import \"application\""] : []
227
+ }
228
+
213
229
  function importmapPlugin() {
214
230
  return {
215
231
  name: "rails-jsdom-importmap",
@@ -221,7 +237,11 @@ function importmapPlugin() {
221
237
  }
222
238
 
223
239
  function unresolvedImport(args) {
224
- return args.kind === "dynamic-import" ? { path: args.path, external: true } : undefined
240
+ return args.kind === "dynamic-import" && !bundlesFromNodeModules(args.path) ? { path: args.path, external: true } : undefined
241
+ }
242
+
243
+ function bundlesFromNodeModules(specifier) {
244
+ return Boolean(config.entry) && !URL_SPECIFIER.test(specifier)
225
245
  }
226
246
 
227
247
  function resolveImport(specifier) {
@@ -442,10 +462,18 @@ function requestRails(request) {
442
462
  nextFetchId += 1
443
463
  return track(new Promise(resolve => {
444
464
  replies.set(id, resolve)
445
- send({ type: "fetch", id, request })
465
+ send({ type: "fetch", id, request: withReferer(request) })
446
466
  }))
447
467
  }
448
468
 
469
+ function withReferer(request) {
470
+ if (!page || !request.headers || "referer" in request.headers) return request
471
+ const location = new page.window.URL(page.window.location.href)
472
+ if (location.origin !== new page.window.URL(request.url).origin) return request
473
+ location.hash = ""
474
+ return { ...request, headers: { ...request.headers, referer: location.href } }
475
+ }
476
+
449
477
  function sessionNamed(name) {
450
478
  if (!sessions.has(name)) sessions.set(name, { page: null, back: [], forward: [], storage: { localStorage: new Map(), sessionStorage: new Map() } })
451
479
  return sessions.get(name)
@@ -557,6 +585,17 @@ function prepare(window, current) {
557
585
  fireResourceLoads(window, current.clock)
558
586
  }
559
587
 
588
+ function followLocationNavigations(window) {
589
+ const location = wrappers.implForWrapper(window.location)
590
+ const navigateInDocument = location._locationObjectNavigate.bind(location)
591
+ location._locationObjectNavigate = (record, options = {}) => {
592
+ const url = urls.serializeURL(record)
593
+ if (staysInDocument(window, url) || !["http:", "https:"].includes(new window.URL(url).protocol)) return navigateInDocument(record, options)
594
+ navigate({ method: "GET", url }, options.replacement ? "none" : "push")
595
+ }
596
+ location.reload = () => navigate({ method: "GET", url: window.location.href }, "none")
597
+ }
598
+
560
599
  function addVirtualTime(window) {
561
600
  const RealDate = window.Date
562
601
  const current = () => time.epoch + time.now
@@ -578,6 +617,7 @@ function trackHistory(window, current) {
578
617
  current.position += 1
579
618
  current.length = current.position + 1
580
619
  }
620
+ followLocationNavigations(window)
581
621
  }
582
622
 
583
623
  function addFormParticipation(window) {
@@ -680,8 +720,50 @@ function addFullscreen(window) {
680
720
  }
681
721
  }
682
722
 
723
+ function addFormMethod(window) {
724
+ for (const prototype of [window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype]) {
725
+ Object.defineProperty(prototype, "formMethod", {
726
+ configurable: true,
727
+ get() {
728
+ const method = this.getAttribute("formmethod")?.toLowerCase()
729
+ if (method === undefined) return ""
730
+ return ["get", "post", "dialog"].includes(method) ? method : "get"
731
+ },
732
+ set(method) { this.setAttribute("formmethod", method) }
733
+ })
734
+ }
735
+ }
736
+
737
+ function addInlineHandlerAdoption(window) {
738
+ const adoptNode = window.Document.prototype.adoptNode
739
+ window.Document.prototype.adoptNode = function (node) {
740
+ const adopted = adoptNode.call(this, node)
741
+ const elements = adopted.nodeType === 1 ? [adopted, ...adopted.querySelectorAll("*")] : [...adopted.querySelectorAll?.("*") ?? []]
742
+ elements.forEach(recompileInlineHandlers)
743
+ return adopted
744
+ }
745
+ }
746
+
747
+ function recompileInlineHandlers(element) {
748
+ for (const { name, value } of [...element.attributes]) {
749
+ if (name.startsWith("on")) element.setAttribute(name, value)
750
+ }
751
+ }
752
+
683
753
  function addContentEditable(window) {
684
754
  Object.defineProperty(window.HTMLElement.prototype, "isContentEditable", { configurable: true, get() { return Boolean(editingHost(this)) } })
755
+ Object.defineProperty(window.HTMLElement.prototype, "contentEditable", {
756
+ configurable: true,
757
+ get() {
758
+ const value = this.getAttribute("contenteditable")?.toLowerCase()
759
+ if (value === "" || value === "true") return "true"
760
+ return ["false", "plaintext-only"].includes(value) ? value : "inherit"
761
+ },
762
+ set(value) {
763
+ if (String(value).toLowerCase() === "inherit") this.removeAttribute("contenteditable")
764
+ else this.setAttribute("contenteditable", String(value))
765
+ }
766
+ })
685
767
  }
686
768
 
687
769
  function removeTouchSupport(window) {
@@ -699,6 +781,8 @@ function deleteFromChain(object, name) {
699
781
 
700
782
  function stubMissingBrowserApis(window) {
701
783
  addFormParticipation(window)
784
+ addFormMethod(window)
785
+ addInlineHandlerAdoption(window)
702
786
  addContentEditable(window)
703
787
  addFullscreen(window)
704
788
  removeTouchSupport(window)
@@ -806,9 +890,22 @@ function dataType(format) {
806
890
  }
807
891
 
808
892
  function addDialogMethods(window) {
809
- window.HTMLDialogElement.prototype.show = window.HTMLDialogElement.prototype.showModal = function () { this.setAttribute("open", "") }
893
+ const modals = []
894
+ openModals.set(window, modals)
895
+ const returnValues = new WeakMap()
896
+ Object.defineProperty(window.HTMLDialogElement.prototype, "returnValue", {
897
+ configurable: true,
898
+ get() { return returnValues.get(this) ?? "" },
899
+ set(value) { returnValues.set(this, String(value)) }
900
+ })
901
+ window.HTMLDialogElement.prototype.show = function () { this.setAttribute("open", "") }
902
+ window.HTMLDialogElement.prototype.showModal = function () {
903
+ this.setAttribute("open", "")
904
+ modals.push(this)
905
+ }
810
906
  window.HTMLDialogElement.prototype.close = function (returnValue) {
811
907
  if (returnValue !== undefined) this.returnValue = returnValue
908
+ if (modals.includes(this)) modals.splice(modals.indexOf(this), 1)
812
909
  if (this.hasAttribute("open")) {
813
910
  this.removeAttribute("open")
814
911
  this.dispatchEvent(new window.Event("close"))
@@ -816,6 +913,12 @@ function addDialogMethods(window) {
816
913
  }
817
914
  }
818
915
 
916
+ function cancelTopModal(window) {
917
+ const dialog = openModals.get(window).findLast(modal => modal.isConnected && modal.hasAttribute("open"))
918
+ if (dialog && dialog.dispatchEvent(new window.Event("cancel", { cancelable: true }))) dialog.close()
919
+ return null
920
+ }
921
+
819
922
  function addMessageChannel(window, clock) {
820
923
  const peers = new WeakMap()
821
924
  const closed = new WeakSet()
@@ -852,8 +955,19 @@ function receiveMessage(window, port, data, closed) {
852
955
 
853
956
  function boot(window, report) {
854
957
  const { Application, controllers } = window.RailsJsdomBundle
958
+ if (config.controllers) registerControllers(window, Application, controllers, report)
959
+ else Application.prototype.handleError = stimulusErrorReporter(report)
960
+ fallBackLast(window, "click", event => followLink(window, event))
961
+ fallBackLast(window, "submit", event => submitUnhandled(event))
962
+ }
963
+
964
+ function stimulusErrorReporter(report) {
965
+ return (error, message) => report(new Error(`${message}: ${describeError(error)}`))
966
+ }
967
+
968
+ function registerControllers(window, Application, controllers, report) {
855
969
  const application = window.Stimulus instanceof Application ? window.Stimulus : Application.start()
856
- application.handleError = (error, message) => report(new Error(`${message}: ${describeError(error)}`))
970
+ application.handleError = stimulusErrorReporter(report)
857
971
  window.Stimulus = application
858
972
  const registered = new Set()
859
973
  const register = identifier => {
@@ -866,8 +980,6 @@ function boot(window, report) {
866
980
  discover()
867
981
  new window.MutationObserver(discover).observe(window.document, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-controller"] })
868
982
  })
869
- fallBackLast(window, "click", event => followLink(window, event))
870
- fallBackLast(window, "submit", event => submitUnhandled(event))
871
983
  }
872
984
 
873
985
  function registerInTurn(window, identifiers, register, done) {
@@ -1150,7 +1262,11 @@ function find({ locator, scope, match }, strategy, kind) {
1150
1262
  const description = locator === null ? "any element of that kind" : JSON.stringify(locator)
1151
1263
  const candidates = locator === null ? [...root.querySelectorAll(kind || CLICKABLE)] : located(root, locator, strategy, kind)
1152
1264
  if (candidates.length === 0) throw new Error(`RailsJsdom: unable to find ${description}`)
1153
- return pick(candidates, description, match)
1265
+ const usable = candidates.filter(element => !element.disabled && isVisible(element))
1266
+ if (usable.length > 0) return pick(usable, description, match)
1267
+ const shown = candidates.filter(element => isVisible(element) || element.matches("input[type=file]"))
1268
+ if (shown.length === 0) throw new Error(`RailsJsdom: unable to find ${description}: every match is hidden`)
1269
+ return pick(shown, description, match)
1154
1270
  }
1155
1271
 
1156
1272
  function located(root, locator, strategy, kind) {
@@ -1158,7 +1274,12 @@ function located(root, locator, strategy, kind) {
1158
1274
  }
1159
1275
 
1160
1276
  function scopeRoot(scope = []) {
1161
- return scope.reduce((parent, entry) => only(scoped(parent, entry), `within ${JSON.stringify(entry)}`), page.window.document)
1277
+ return scope.reduce((parent, entry) => only(preferVisible(scoped(parent, entry)), `within ${JSON.stringify(entry)}`), page.window.document)
1278
+ }
1279
+
1280
+ function preferVisible(elements) {
1281
+ const visible = elements.filter(isVisible)
1282
+ return visible.length > 0 ? visible : elements
1162
1283
  }
1163
1284
 
1164
1285
  function scoped(parent, entry) {
@@ -1205,11 +1326,16 @@ function byClickable(root, text) {
1205
1326
 
1206
1327
  function byField(root, text) {
1207
1328
  const fields = [...root.querySelectorAll(FIELDS)]
1208
- const labelled = byText([...root.querySelectorAll("label")], text).map(label => label.control).filter(Boolean)
1329
+ const labelled = [...new Set(byText([...root.querySelectorAll("label")], text).flatMap(labelledFields))]
1209
1330
  const attributes = ["placeholder", "name", "id", "aria-label"].map(attribute => fields.filter(field => field.getAttribute(attribute) === text))
1210
1331
  return [labelled, ...attributes].find(list => list.length > 0) || []
1211
1332
  }
1212
1333
 
1334
+ function labelledFields(label) {
1335
+ if (!label.htmlFor) return label.control ? [label.control] : []
1336
+ return [...label.ownerDocument.querySelectorAll(FIELDS)].filter(field => field.id === label.htmlFor)
1337
+ }
1338
+
1213
1339
  function click(element) {
1214
1340
  const window = element.ownerDocument.defaultView
1215
1341
  const options = { bubbles: true, cancelable: true, composed: true, view: window }
@@ -1224,10 +1350,14 @@ function click(element) {
1224
1350
  function fill(element, value) {
1225
1351
  if (element.disabled || element.readOnly) throw new Error(`RailsJsdom: ${element.outerHTML.slice(0, 120)} is not editable`)
1226
1352
  element.focus()
1227
- element.value = value
1353
+ setNativeValue(element, value)
1228
1354
  changed(element)
1229
1355
  }
1230
1356
 
1357
+ function setNativeValue(element, value) {
1358
+ Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element), "value").set.call(element, value)
1359
+ }
1360
+
1231
1361
  function changed(element) {
1232
1362
  const window = element.ownerDocument.defaultView
1233
1363
  element.dispatchEvent(new window.Event("input", { bubbles: true }))
@@ -1416,6 +1546,7 @@ function press(key, modifiers) {
1416
1546
 
1417
1547
  function keyAction(target, key, modifiers) {
1418
1548
  if (key === "Tab") return moveFocus(target, modifiers.shiftKey)
1549
+ if (key === "Escape") return cancelTopModal(target.ownerDocument.defaultView)
1419
1550
  const host = editingHost(target)
1420
1551
  return host ? editContent(host, key, modifiers) : fieldKeyAction(target, key, modifiers)
1421
1552
  }
@@ -1507,7 +1638,7 @@ function editText(target, key, modifiers) {
1507
1638
  const before = target.value
1508
1639
  const after = editedValue(before, key, modifiers)
1509
1640
  if (after === before) return null
1510
- target.value = after
1641
+ setNativeValue(target, after)
1511
1642
  if (!page.edited.has(target)) page.edited.set(target, before)
1512
1643
  const deleting = key === "Backspace"
1513
1644
  return target.dispatchEvent(new target.ownerDocument.defaultView.InputEvent("input", { bubbles: true, inputType: deleting ? "deleteContentBackward" : "insertText", data: deleting ? null : key }))
@@ -1527,7 +1658,7 @@ function pressEnter(target) {
1527
1658
  if (target.matches(`a[href], ${KINDS.button}`)) return click(target)
1528
1659
  const form = target.form
1529
1660
  if (!form || !target.matches(FILLABLE)) return null
1530
- const submitter = form.querySelector(`button:not([type]), button[type=submit], input[type=submit], input[type=image]`)
1661
+ const submitter = [...form.elements].find(element => element.matches(`button:not([type]), button[type=submit], input[type=submit], input[type=image]`))
1531
1662
  return submitter ? click(submitter) : form.requestSubmit()
1532
1663
  }
1533
1664
 
@@ -1608,7 +1739,11 @@ function snapshot(scope) {
1608
1739
  if (!page) throw new Error("RailsJsdom: visit a page or mount a partial first")
1609
1740
  const root = scopeRoot(scope)
1610
1741
  const document = root.nodeType === 9
1611
- return { html: document ? page.dom.serialize() : root.outerHTML, text: normalize(visibleText(document ? root.body : root)), url: page.window.location.href, title: page.window.document.title }
1742
+ return { html: document ? page.dom.serialize() : root.outerHTML, text: normalize(document ? renderedText(root) : visibleText(root)), url: page.window.location.href, title: page.window.document.title }
1743
+ }
1744
+
1745
+ function renderedText(document) {
1746
+ return [...document.documentElement.childNodes].filter(node => node.localName !== "head").map(visibleText).join("")
1612
1747
  }
1613
1748
 
1614
1749
  module.exports = { start }
@@ -77,6 +77,10 @@ module RailsJsdom
77
77
  rails_jsdom_visit(path, "push")
78
78
  end
79
79
 
80
+ def header(name, value)
81
+ rails_jsdom_headers[name.to_s.downcase] = value
82
+ end
83
+
80
84
  # Requests the current URL again and loads it as a new page, without
81
85
  # adding a history entry.
82
86
  def refresh
@@ -827,7 +831,12 @@ module RailsJsdom
827
831
  { status: response.status, headers: response.headers.to_h.except("set-cookie"), body: response.body, url: request.original_url, redirected: redirected }
828
832
  end
829
833
 
834
+ def rails_jsdom_headers
835
+ @rails_jsdom_headers ||= {}
836
+ end
837
+
830
838
  def rails_jsdom_request(method, path, headers:, params: nil)
839
+ headers = rails_jsdom_headers.merge(headers.transform_keys(&:downcase))
831
840
  process(method.downcase.to_sym, path, params: params, headers: headers)
832
841
  rails_jsdom_follow_redirects(headers.except("content-type", "content-encoding", "content-language", "content-location"), false)
833
842
  end
@@ -1,4 +1,4 @@
1
1
  module RailsJsdom
2
2
  # The version of the rails-jsdom gem.
3
- VERSION = "0.2.1".freeze
3
+ VERSION = "0.3.0".freeze
4
4
  end
data/lib/rails_jsdom.rb CHANGED
@@ -29,6 +29,16 @@ module RailsJsdom
29
29
 
30
30
  class << self
31
31
  attr_writer :command_timeout
32
+ attr_accessor :entry, :esbuild_config
33
+ attr_writer :register_controllers, :hidden_selectors
34
+
35
+ def hidden_selectors
36
+ @hidden_selectors || []
37
+ end
38
+
39
+ def register_controllers?
40
+ @register_controllers != false
41
+ end
32
42
 
33
43
  # Seconds to wait for the page to answer a command. A page in an endless
34
44
  # loop never answers; after this long its Node process is stopped and the
@@ -45,12 +55,14 @@ module RailsJsdom
45
55
  {
46
56
  command: "setup",
47
57
  root: Rails.root.to_s,
48
- controllers: Rails.root.join("app/javascript/controllers").to_s,
58
+ controllers: controllers,
59
+ entry: app_path(entry),
60
+ esbuild: app_path(esbuild_config),
49
61
  modules: modules,
50
62
  stubs: remote_modules,
51
63
  directories: directories,
52
64
  horizon: TIMER_HORIZON,
53
- hidden: HIDDEN_SELECTOR
65
+ hidden: [ HIDDEN_SELECTOR, *hidden_selectors ].join(", ")
54
66
  }
55
67
  end
56
68
 
@@ -63,7 +75,11 @@ module RailsJsdom
63
75
  end
64
76
 
65
77
  def directories
66
- Rails.application.importmap.directories.values.to_h { |directory| [ directory.under, Rails.root.join(directory.dir).to_s ] }
78
+ importmap_directories.to_h { |directory| [ directory.under, Rails.root.join(directory.dir).to_s ] }
79
+ end
80
+
81
+ def controllers
82
+ Rails.root.join("app/javascript/controllers").to_s if register_controllers?
67
83
  end
68
84
 
69
85
  def reject_options(keywords) # :nodoc:
@@ -91,7 +107,17 @@ module RailsJsdom
91
107
  end
92
108
 
93
109
  def packages
94
- Rails.application.importmap.packages.transform_values(&:path)
110
+ importmap = Rails.application.try(:importmap)
111
+ importmap ? importmap.packages.transform_values(&:path) : {}
112
+ end
113
+
114
+ def importmap_directories
115
+ importmap = Rails.application.try(:importmap)
116
+ importmap ? importmap.directories.values : []
117
+ end
118
+
119
+ def app_path(path)
120
+ Rails.root.join(path).to_s if path
95
121
  end
96
122
 
97
123
  def bridges
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rails-jsdom
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.1
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jake Howerton