rails-jsdom 0.2.1 → 0.3.1

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: 7fc4428dc052f17cd0c104a9f4712ec1021ed0595f7568b81ce94332e3b89fb3
4
+ data.tar.gz: 63c7b612afe81fb9ec93e08443a728c4f0d82d7f1633484ebd55b16761d29850
5
5
  SHA512:
6
- metadata.gz: 9f3317df6c4401589b032c5aa07e7d5ca29a7ce82033df5722645f71c70f31543457c6ff020d267bbdc5dc021a3f5953fe5684ef3e1276bbe9108a8fce955839
7
- data.tar.gz: f9b5a3bb28b8f161ad5069591d56ad83d0930562a174453b1cef568e5fa9276eea40b48d2e7d8b968ed72573ba4c59bf8306b18e254ba34881bfc2b87168948d
6
+ metadata.gz: 552c35d2b8dbf2a16c3411dc9114621fd4dd7867ead9739ec077102c00e56dbf68b417ba9d10630697d834a8988a60b77bdf71f66e796782f50016f3e0e43675
7
+ data.tar.gz: 3c65b0ad230fdbb3cbb94809f3456a4b20fbb45d1b9a5b86543f96cce31d9eebaea799d3912224b152f91d2ce77cf785b0f438e73648bb7bd728fc84125a6078
data/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1 (2026-11-30)
4
+
5
+ ### Fixed
6
+
7
+ - Importing an importmap pin whose file is not in the asset load path, such as `pin "blocks/pele", to: "pele_block.js"` before `pele_block.js` exists or is built, fails with an error that names the pin and its file, when the import runs, as in a browser. Before, building the bundle failed with a path nobody wrote, such as `Cannot read file: app/javascript/blocks/pele.js` when a `pin_all_from` directory shared the pin's prefix, and a dynamic import of it failed with no word of the pin. A file of the pin's name in a `pin_all_from` directory is still used instead, as importmap-rails maps it.
8
+
9
+ ## 0.3.0 (2026-11-28)
10
+
11
+ ### Added
12
+
13
+ - 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`.
14
+ - `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.
15
+ - `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.
16
+ - An app without importmap configured gets no pins instead of an error.
17
+ - `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.
18
+ - `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.
19
+
20
+ ### Changed
21
+
22
+ - 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".
23
+ - 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.
24
+ - `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.
25
+
26
+ ### Fixed
27
+
28
+ - 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.
29
+ - 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.
30
+ - 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.
31
+ - 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.
32
+ - 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.
33
+ - `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.
34
+ - `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.
35
+ - 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.
36
+ - 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.
37
+ - 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.
38
+ - 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.
39
+ - 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.
40
+ - 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.
41
+
3
42
  ## 0.2.1 (2026-11-14)
4
43
 
5
44
  ### 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,8 +5,10 @@ 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"
11
+ const MISSING_NAMESPACE = "rails-jsdom-missing-pin"
10
12
  const STUB_SOURCE = "module.exports = Object.create(new Proxy({}, { get: (target, key) => typeof key === 'symbol' || key === 'then' || key === '__esModule' ? undefined : () => {} }))"
11
13
  const STIMULUS_LOADING = "@hotwired/stimulus-loading"
12
14
  const INLINE_ELEMENTS = new Set(["a", "abbr", "b", "bdi", "bdo", "cite", "code", "data", "dfn", "em", "i", "kbd", "label", "mark", "output", "q", "s", "samp", "small", "span", "strong", "sub", "sup", "time", "u", "var"])
@@ -28,9 +30,11 @@ const SETTLE_LIMIT = 10000
28
30
  const MEASUREMENT_LIMIT = 10000
29
31
  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
32
  const LOADABLE = "link[rel~=stylesheet], img[src]:not([src=\"\"])"
33
+ const URL_SPECIFIER = /^[a-z][a-z0-9+.-]*:/i
31
34
 
32
35
  const replies = new Map()
33
36
  const fetchStubs = new Map()
37
+ const openModals = new WeakMap()
34
38
  const pending = new Set()
35
39
  const errors = []
36
40
  const owners = new WeakMap()
@@ -44,6 +48,7 @@ let inbox = []
44
48
  let config = null
45
49
  let jsdom = null
46
50
  let wrappers = null
51
+ let urls = null
47
52
  let bundle = null
48
53
  let page = null
49
54
  const sessions = new Map()
@@ -174,8 +179,9 @@ async function setup(message) {
174
179
  const appRequire = createRequire(path.join(config.root, "package.json"))
175
180
  jsdom = appRequire("jsdom")
176
181
  wrappers = appRequire("jsdom/lib/generated/idl/utils.js")
182
+ urls = createRequire(appRequire.resolve("jsdom"))("whatwg-url")
177
183
  const esbuild = appRequire("esbuild")
178
- const result = await esbuild.build({
184
+ const result = await esbuild.build(await configureBuild({
179
185
  stdin: { contents: entrySource(), resolveDir: config.root, sourcefile: "rails-jsdom-entry.js", loader: "js" },
180
186
  bundle: true,
181
187
  write: false,
@@ -183,11 +189,17 @@ async function setup(message) {
183
189
  globalName: "RailsJsdomBundle",
184
190
  logLevel: "silent",
185
191
  plugins: [importmapPlugin()]
186
- })
192
+ }))
187
193
  bundle = new vm.Script(result.outputFiles[0].text, { filename: "rails-jsdom-bundle.js" })
188
194
  return {}
189
195
  }
190
196
 
197
+ async function configureBuild(options) {
198
+ if (!config.esbuild) return options
199
+ const { default: configure } = await import(pathToFileURL(config.esbuild).href)
200
+ return await configure(options)
201
+ }
202
+
191
203
  function controllerFiles(directory, prefix) {
192
204
  return fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap(entry => {
193
205
  if (entry.isDirectory()) return controllerFiles(path.join(directory, entry.name), `${prefix}${entry.name}/`)
@@ -200,37 +212,61 @@ function identifierFor(relative) {
200
212
  }
201
213
 
202
214
  function entrySource() {
203
- const files = controllerFiles(config.controllers, "")
215
+ const files = config.controllers ? controllerFiles(config.controllers, "") : []
204
216
  return [
205
217
  "import \"@hotwired/turbo-rails\"",
206
218
  "export { Application } from \"@hotwired/stimulus\"",
207
219
  ...files.map(([, file], index) => `import controller${index} from ${JSON.stringify(file)}`),
208
220
  `export const controllers = { ${files.map(([relative], index) => `${JSON.stringify(identifierFor(relative))}: controller${index}`).join(", ")} }`,
209
- ...(config.modules.application ? ["import \"application\""] : [])
221
+ ...applicationImport()
210
222
  ].join("\n")
211
223
  }
212
224
 
225
+ function applicationImport() {
226
+ if (config.entry) return [`import ${JSON.stringify(config.entry)}`]
227
+ return config.modules.application ? ["import \"application\""] : []
228
+ }
229
+
213
230
  function importmapPlugin() {
214
231
  return {
215
232
  name: "rails-jsdom-importmap",
216
233
  setup(build) {
217
234
  build.onResolve({ filter: /^[^./]/ }, args => resolveImport(args.path) ?? unresolvedImport(args))
218
235
  build.onLoad({ filter: /.*/, namespace: STUB_NAMESPACE }, () => ({ contents: STUB_SOURCE, loader: "js" }))
236
+ build.onLoad({ filter: /.*/, namespace: MISSING_NAMESPACE }, args => ({ contents: missingPinSource(args.path), loader: "js" }))
219
237
  }
220
238
  }
221
239
  }
222
240
 
223
241
  function unresolvedImport(args) {
224
- return args.kind === "dynamic-import" ? { path: args.path, external: true } : undefined
242
+ return args.kind === "dynamic-import" && !bundlesFromNodeModules(args.path) ? { path: args.path, external: true } : undefined
243
+ }
244
+
245
+ function bundlesFromNodeModules(specifier) {
246
+ return Boolean(config.entry) && !URL_SPECIFIER.test(specifier)
225
247
  }
226
248
 
227
249
  function resolveImport(specifier) {
228
- const directory = Object.keys(config.directories).find(prefix => specifier.startsWith(`${prefix}/`))
229
250
  if (specifier === STIMULUS_LOADING || config.stubs.includes(specifier)) return { path: specifier, namespace: STUB_NAMESPACE }
230
251
  if (config.modules[specifier]) return { path: config.modules[specifier] }
231
252
  if (config.directories[specifier]) return { path: path.join(config.directories[specifier], "index.js") }
232
- if (directory) return { path: `${path.join(config.directories[directory], specifier.slice(directory.length + 1))}.js` }
233
- return undefined
253
+ return directoryImport(specifier, directoryFile(specifier))
254
+ }
255
+
256
+ function directoryFile(specifier) {
257
+ const directory = Object.keys(config.directories).find(prefix => specifier.startsWith(`${prefix}/`))
258
+ return directory ? `${path.join(config.directories[directory], specifier.slice(directory.length + 1))}.js` : undefined
259
+ }
260
+
261
+ function directoryImport(specifier, file) {
262
+ const target = config.missing[specifier]
263
+ if (target && !(file && fs.existsSync(file))) return { path: specifier, namespace: MISSING_NAMESPACE }
264
+ return file ? { path: file } : undefined
265
+ }
266
+
267
+ function missingPinSource(specifier) {
268
+ const message = `RailsJsdom: pin "${specifier}" points to "${config.missing[specifier]}", which is not in the asset load path. Create the file, build your assets if a build step makes it, or remove the pin.`
269
+ return `throw new Error(${JSON.stringify(message)})`
234
270
  }
235
271
 
236
272
  class Clock {
@@ -442,10 +478,18 @@ function requestRails(request) {
442
478
  nextFetchId += 1
443
479
  return track(new Promise(resolve => {
444
480
  replies.set(id, resolve)
445
- send({ type: "fetch", id, request })
481
+ send({ type: "fetch", id, request: withReferer(request) })
446
482
  }))
447
483
  }
448
484
 
485
+ function withReferer(request) {
486
+ if (!page || !request.headers || "referer" in request.headers) return request
487
+ const location = new page.window.URL(page.window.location.href)
488
+ if (location.origin !== new page.window.URL(request.url).origin) return request
489
+ location.hash = ""
490
+ return { ...request, headers: { ...request.headers, referer: location.href } }
491
+ }
492
+
449
493
  function sessionNamed(name) {
450
494
  if (!sessions.has(name)) sessions.set(name, { page: null, back: [], forward: [], storage: { localStorage: new Map(), sessionStorage: new Map() } })
451
495
  return sessions.get(name)
@@ -557,6 +601,17 @@ function prepare(window, current) {
557
601
  fireResourceLoads(window, current.clock)
558
602
  }
559
603
 
604
+ function followLocationNavigations(window) {
605
+ const location = wrappers.implForWrapper(window.location)
606
+ const navigateInDocument = location._locationObjectNavigate.bind(location)
607
+ location._locationObjectNavigate = (record, options = {}) => {
608
+ const url = urls.serializeURL(record)
609
+ if (staysInDocument(window, url) || !["http:", "https:"].includes(new window.URL(url).protocol)) return navigateInDocument(record, options)
610
+ navigate({ method: "GET", url }, options.replacement ? "none" : "push")
611
+ }
612
+ location.reload = () => navigate({ method: "GET", url: window.location.href }, "none")
613
+ }
614
+
560
615
  function addVirtualTime(window) {
561
616
  const RealDate = window.Date
562
617
  const current = () => time.epoch + time.now
@@ -578,6 +633,7 @@ function trackHistory(window, current) {
578
633
  current.position += 1
579
634
  current.length = current.position + 1
580
635
  }
636
+ followLocationNavigations(window)
581
637
  }
582
638
 
583
639
  function addFormParticipation(window) {
@@ -680,8 +736,50 @@ function addFullscreen(window) {
680
736
  }
681
737
  }
682
738
 
739
+ function addFormMethod(window) {
740
+ for (const prototype of [window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype]) {
741
+ Object.defineProperty(prototype, "formMethod", {
742
+ configurable: true,
743
+ get() {
744
+ const method = this.getAttribute("formmethod")?.toLowerCase()
745
+ if (method === undefined) return ""
746
+ return ["get", "post", "dialog"].includes(method) ? method : "get"
747
+ },
748
+ set(method) { this.setAttribute("formmethod", method) }
749
+ })
750
+ }
751
+ }
752
+
753
+ function addInlineHandlerAdoption(window) {
754
+ const adoptNode = window.Document.prototype.adoptNode
755
+ window.Document.prototype.adoptNode = function (node) {
756
+ const adopted = adoptNode.call(this, node)
757
+ const elements = adopted.nodeType === 1 ? [adopted, ...adopted.querySelectorAll("*")] : [...adopted.querySelectorAll?.("*") ?? []]
758
+ elements.forEach(recompileInlineHandlers)
759
+ return adopted
760
+ }
761
+ }
762
+
763
+ function recompileInlineHandlers(element) {
764
+ for (const { name, value } of [...element.attributes]) {
765
+ if (name.startsWith("on")) element.setAttribute(name, value)
766
+ }
767
+ }
768
+
683
769
  function addContentEditable(window) {
684
770
  Object.defineProperty(window.HTMLElement.prototype, "isContentEditable", { configurable: true, get() { return Boolean(editingHost(this)) } })
771
+ Object.defineProperty(window.HTMLElement.prototype, "contentEditable", {
772
+ configurable: true,
773
+ get() {
774
+ const value = this.getAttribute("contenteditable")?.toLowerCase()
775
+ if (value === "" || value === "true") return "true"
776
+ return ["false", "plaintext-only"].includes(value) ? value : "inherit"
777
+ },
778
+ set(value) {
779
+ if (String(value).toLowerCase() === "inherit") this.removeAttribute("contenteditable")
780
+ else this.setAttribute("contenteditable", String(value))
781
+ }
782
+ })
685
783
  }
686
784
 
687
785
  function removeTouchSupport(window) {
@@ -699,6 +797,8 @@ function deleteFromChain(object, name) {
699
797
 
700
798
  function stubMissingBrowserApis(window) {
701
799
  addFormParticipation(window)
800
+ addFormMethod(window)
801
+ addInlineHandlerAdoption(window)
702
802
  addContentEditable(window)
703
803
  addFullscreen(window)
704
804
  removeTouchSupport(window)
@@ -806,9 +906,22 @@ function dataType(format) {
806
906
  }
807
907
 
808
908
  function addDialogMethods(window) {
809
- window.HTMLDialogElement.prototype.show = window.HTMLDialogElement.prototype.showModal = function () { this.setAttribute("open", "") }
909
+ const modals = []
910
+ openModals.set(window, modals)
911
+ const returnValues = new WeakMap()
912
+ Object.defineProperty(window.HTMLDialogElement.prototype, "returnValue", {
913
+ configurable: true,
914
+ get() { return returnValues.get(this) ?? "" },
915
+ set(value) { returnValues.set(this, String(value)) }
916
+ })
917
+ window.HTMLDialogElement.prototype.show = function () { this.setAttribute("open", "") }
918
+ window.HTMLDialogElement.prototype.showModal = function () {
919
+ this.setAttribute("open", "")
920
+ modals.push(this)
921
+ }
810
922
  window.HTMLDialogElement.prototype.close = function (returnValue) {
811
923
  if (returnValue !== undefined) this.returnValue = returnValue
924
+ if (modals.includes(this)) modals.splice(modals.indexOf(this), 1)
812
925
  if (this.hasAttribute("open")) {
813
926
  this.removeAttribute("open")
814
927
  this.dispatchEvent(new window.Event("close"))
@@ -816,6 +929,12 @@ function addDialogMethods(window) {
816
929
  }
817
930
  }
818
931
 
932
+ function cancelTopModal(window) {
933
+ const dialog = openModals.get(window).findLast(modal => modal.isConnected && modal.hasAttribute("open"))
934
+ if (dialog && dialog.dispatchEvent(new window.Event("cancel", { cancelable: true }))) dialog.close()
935
+ return null
936
+ }
937
+
819
938
  function addMessageChannel(window, clock) {
820
939
  const peers = new WeakMap()
821
940
  const closed = new WeakSet()
@@ -852,8 +971,19 @@ function receiveMessage(window, port, data, closed) {
852
971
 
853
972
  function boot(window, report) {
854
973
  const { Application, controllers } = window.RailsJsdomBundle
974
+ if (config.controllers) registerControllers(window, Application, controllers, report)
975
+ else Application.prototype.handleError = stimulusErrorReporter(report)
976
+ fallBackLast(window, "click", event => followLink(window, event))
977
+ fallBackLast(window, "submit", event => submitUnhandled(event))
978
+ }
979
+
980
+ function stimulusErrorReporter(report) {
981
+ return (error, message) => report(new Error(`${message}: ${describeError(error)}`))
982
+ }
983
+
984
+ function registerControllers(window, Application, controllers, report) {
855
985
  const application = window.Stimulus instanceof Application ? window.Stimulus : Application.start()
856
- application.handleError = (error, message) => report(new Error(`${message}: ${describeError(error)}`))
986
+ application.handleError = stimulusErrorReporter(report)
857
987
  window.Stimulus = application
858
988
  const registered = new Set()
859
989
  const register = identifier => {
@@ -866,8 +996,6 @@ function boot(window, report) {
866
996
  discover()
867
997
  new window.MutationObserver(discover).observe(window.document, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-controller"] })
868
998
  })
869
- fallBackLast(window, "click", event => followLink(window, event))
870
- fallBackLast(window, "submit", event => submitUnhandled(event))
871
999
  }
872
1000
 
873
1001
  function registerInTurn(window, identifiers, register, done) {
@@ -1150,7 +1278,11 @@ function find({ locator, scope, match }, strategy, kind) {
1150
1278
  const description = locator === null ? "any element of that kind" : JSON.stringify(locator)
1151
1279
  const candidates = locator === null ? [...root.querySelectorAll(kind || CLICKABLE)] : located(root, locator, strategy, kind)
1152
1280
  if (candidates.length === 0) throw new Error(`RailsJsdom: unable to find ${description}`)
1153
- return pick(candidates, description, match)
1281
+ const usable = candidates.filter(element => !element.disabled && isVisible(element))
1282
+ if (usable.length > 0) return pick(usable, description, match)
1283
+ const shown = candidates.filter(element => isVisible(element) || element.matches("input[type=file]"))
1284
+ if (shown.length === 0) throw new Error(`RailsJsdom: unable to find ${description}: every match is hidden`)
1285
+ return pick(shown, description, match)
1154
1286
  }
1155
1287
 
1156
1288
  function located(root, locator, strategy, kind) {
@@ -1158,7 +1290,12 @@ function located(root, locator, strategy, kind) {
1158
1290
  }
1159
1291
 
1160
1292
  function scopeRoot(scope = []) {
1161
- return scope.reduce((parent, entry) => only(scoped(parent, entry), `within ${JSON.stringify(entry)}`), page.window.document)
1293
+ return scope.reduce((parent, entry) => only(preferVisible(scoped(parent, entry)), `within ${JSON.stringify(entry)}`), page.window.document)
1294
+ }
1295
+
1296
+ function preferVisible(elements) {
1297
+ const visible = elements.filter(isVisible)
1298
+ return visible.length > 0 ? visible : elements
1162
1299
  }
1163
1300
 
1164
1301
  function scoped(parent, entry) {
@@ -1205,11 +1342,16 @@ function byClickable(root, text) {
1205
1342
 
1206
1343
  function byField(root, text) {
1207
1344
  const fields = [...root.querySelectorAll(FIELDS)]
1208
- const labelled = byText([...root.querySelectorAll("label")], text).map(label => label.control).filter(Boolean)
1345
+ const labelled = [...new Set(byText([...root.querySelectorAll("label")], text).flatMap(labelledFields))]
1209
1346
  const attributes = ["placeholder", "name", "id", "aria-label"].map(attribute => fields.filter(field => field.getAttribute(attribute) === text))
1210
1347
  return [labelled, ...attributes].find(list => list.length > 0) || []
1211
1348
  }
1212
1349
 
1350
+ function labelledFields(label) {
1351
+ if (!label.htmlFor) return label.control ? [label.control] : []
1352
+ return [...label.ownerDocument.querySelectorAll(FIELDS)].filter(field => field.id === label.htmlFor)
1353
+ }
1354
+
1213
1355
  function click(element) {
1214
1356
  const window = element.ownerDocument.defaultView
1215
1357
  const options = { bubbles: true, cancelable: true, composed: true, view: window }
@@ -1224,10 +1366,14 @@ function click(element) {
1224
1366
  function fill(element, value) {
1225
1367
  if (element.disabled || element.readOnly) throw new Error(`RailsJsdom: ${element.outerHTML.slice(0, 120)} is not editable`)
1226
1368
  element.focus()
1227
- element.value = value
1369
+ setNativeValue(element, value)
1228
1370
  changed(element)
1229
1371
  }
1230
1372
 
1373
+ function setNativeValue(element, value) {
1374
+ Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element), "value").set.call(element, value)
1375
+ }
1376
+
1231
1377
  function changed(element) {
1232
1378
  const window = element.ownerDocument.defaultView
1233
1379
  element.dispatchEvent(new window.Event("input", { bubbles: true }))
@@ -1416,6 +1562,7 @@ function press(key, modifiers) {
1416
1562
 
1417
1563
  function keyAction(target, key, modifiers) {
1418
1564
  if (key === "Tab") return moveFocus(target, modifiers.shiftKey)
1565
+ if (key === "Escape") return cancelTopModal(target.ownerDocument.defaultView)
1419
1566
  const host = editingHost(target)
1420
1567
  return host ? editContent(host, key, modifiers) : fieldKeyAction(target, key, modifiers)
1421
1568
  }
@@ -1507,7 +1654,7 @@ function editText(target, key, modifiers) {
1507
1654
  const before = target.value
1508
1655
  const after = editedValue(before, key, modifiers)
1509
1656
  if (after === before) return null
1510
- target.value = after
1657
+ setNativeValue(target, after)
1511
1658
  if (!page.edited.has(target)) page.edited.set(target, before)
1512
1659
  const deleting = key === "Backspace"
1513
1660
  return target.dispatchEvent(new target.ownerDocument.defaultView.InputEvent("input", { bubbles: true, inputType: deleting ? "deleteContentBackward" : "insertText", data: deleting ? null : key }))
@@ -1527,7 +1674,7 @@ function pressEnter(target) {
1527
1674
  if (target.matches(`a[href], ${KINDS.button}`)) return click(target)
1528
1675
  const form = target.form
1529
1676
  if (!form || !target.matches(FILLABLE)) return null
1530
- const submitter = form.querySelector(`button:not([type]), button[type=submit], input[type=submit], input[type=image]`)
1677
+ const submitter = [...form.elements].find(element => element.matches(`button:not([type]), button[type=submit], input[type=submit], input[type=image]`))
1531
1678
  return submitter ? click(submitter) : form.requestSubmit()
1532
1679
  }
1533
1680
 
@@ -1608,7 +1755,11 @@ function snapshot(scope) {
1608
1755
  if (!page) throw new Error("RailsJsdom: visit a page or mount a partial first")
1609
1756
  const root = scopeRoot(scope)
1610
1757
  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 }
1758
+ 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 }
1759
+ }
1760
+
1761
+ function renderedText(document) {
1762
+ return [...document.documentElement.childNodes].filter(node => node.localName !== "head").map(visibleText).join("")
1612
1763
  }
1613
1764
 
1614
1765
  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.1".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,17 +55,24 @@ 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,
62
+ missing: missing_modules,
50
63
  stubs: remote_modules,
51
64
  directories: directories,
52
65
  horizon: TIMER_HORIZON,
53
- hidden: HIDDEN_SELECTOR
66
+ hidden: [ HIDDEN_SELECTOR, *hidden_selectors ].join(", ")
54
67
  }
55
68
  end
56
69
 
57
70
  def modules
58
- packages.reject { |_name, path| path.match?(REMOTE) }.transform_values { |path| Rails.application.assets.load_path.find(path)&.path&.to_s }
71
+ local_packages.transform_values { |path| asset_file(path) }
72
+ end
73
+
74
+ def missing_modules
75
+ local_packages.reject { |_name, path| asset_file(path) }
59
76
  end
60
77
 
61
78
  def remote_modules
@@ -63,7 +80,11 @@ module RailsJsdom
63
80
  end
64
81
 
65
82
  def directories
66
- Rails.application.importmap.directories.values.to_h { |directory| [ directory.under, Rails.root.join(directory.dir).to_s ] }
83
+ importmap_directories.to_h { |directory| [ directory.under, Rails.root.join(directory.dir).to_s ] }
84
+ end
85
+
86
+ def controllers
87
+ Rails.root.join("app/javascript/controllers").to_s if register_controllers?
67
88
  end
68
89
 
69
90
  def reject_options(keywords) # :nodoc:
@@ -91,7 +112,25 @@ module RailsJsdom
91
112
  end
92
113
 
93
114
  def packages
94
- Rails.application.importmap.packages.transform_values(&:path)
115
+ importmap = Rails.application.try(:importmap)
116
+ importmap ? importmap.packages.transform_values(&:path) : {}
117
+ end
118
+
119
+ def local_packages
120
+ packages.reject { |_name, path| path.match?(REMOTE) }
121
+ end
122
+
123
+ def asset_file(path)
124
+ Rails.application.assets.load_path.find(path)&.path&.to_s
125
+ end
126
+
127
+ def importmap_directories
128
+ importmap = Rails.application.try(:importmap)
129
+ importmap ? importmap.directories.values : []
130
+ end
131
+
132
+ def app_path(path)
133
+ Rails.root.join(path).to_s if path
95
134
  end
96
135
 
97
136
  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.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jake Howerton