Skip to content

Instantly share code, notes, and snippets.

@justinko
Created September 14, 2024 16:44
Show Gist options
  • Save justinko/0ea35143ec7545c0a9ac99357b0fd5a9 to your computer and use it in GitHub Desktop.
Save justinko/0ea35143ec7545c0a9ac99357b0fd5a9 to your computer and use it in GitHub Desktop.
Capybara wait for JavaScript to be ready
<!DOCTYPE html>
<html>
<body data-controller="test-readiness">
</body>
</html>
import { Turbo } from "@hotwired/turbo-rails"
import { Application } from "@hotwired/stimulus"
const application = Application.start()
// Configure Stimulus development experience
application.debug = false
window.Stimulus = application
function getMetaContent(name) {
const element = document.head.querySelector(`meta[name='${name}']`)
return (element ? element.getAttribute("content") : null)
}
if (getMetaContent("rails-env") === "test") {
Turbo.setProgressBarDelay(0)
}
def assert_readiness
assert_all_of_selectors(:css,
'body[data-stimulus-ready="true"]',
'body[data-javascript-files-loaded="true"]'
)
assert_none_of_selectors(:css,
'.turbo-progress-bar', 'turbo-frame[busy]', visible: false
)
end
# click_on "Create Account"
# assert_readiness
import { Controller } from "@hotwired/stimulus"
import { debounce } from "helpers"
// This is only used during tests. It sets some data-* attribute flags in <body>
// to capture when Hotwire components are initiated. It's meant to offer a mechanism to wait
// for those to Capybara.
export default class extends Controller {
connect() {
this.stimulusIsReady()
this.monitorLoadOfJavascriptFiles()
}
stimulusIsReady() {
this.element.setAttribute("data-stimulus-ready", true)
}
monitorLoadOfJavascriptFiles = debounce(() =>{
const scripts = window.performance.getEntriesByType("resource").filter(resource => resource.name.endsWith(".js"))
if (scripts.every(script => script.responseEnd)) {
this.javascriptFilesWereLoaded()
} else {
this.monitorLoadOfJavascriptFiles()
}
}, 500)
async javascriptFilesWereLoaded() {
this.element.setAttribute("data-javascript-files-loaded", true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment