Module: Dommy::TestHelpers

Defined in:
lib/dommy/test_helpers.rb

Overview

Lightweight helpers for using Dommy from RSpec / Minitest test suites.

Examples:

RSpec

require "dommy/test_helpers"

RSpec.configure do |c|
  c.include Dommy::TestHelpers
end

RSpec.describe MyComponent do
  it "renders the heading" do
    dom = parse_html(render(MyComponent.new))
    expect(dom.query_selector("h1").text_content).to eq("Welcome")
  end
end

Minitest

require "dommy/test_helpers"

class MyComponentTest < Minitest::Test
  include Dommy::TestHelpers

  def test_renders_the_heading
    dom = parse_html(render(MyComponent.new))
    assert_equal "Welcome", dom.query_selector("h1").text_content
  end
end

Instance Method Summary collapse

Instance Method Details

#advance_time(window, ms) ⇒ Object

Advance the window’s virtual clock. Timers that come due and any queued microtasks are run as part of the advance. Use this to test code that schedules work with setTimeout / setInterval.

Parameters:

  • window (Dommy::Window)
  • ms (Integer)

    milliseconds to advance



74
75
76
# File 'lib/dommy/test_helpers.rb', line 74

def advance_time(window, ms)
  window.scheduler.advance_time(ms)
end

#flush_microtasks(window) ⇒ Object

Drain pending microtasks on the window’s scheduler. Use this after a mutation if you need MutationObserver callbacks (scheduled as microtasks) to fire before your assertions.

Parameters:



64
65
66
# File 'lib/dommy/test_helpers.rb', line 64

def flush_microtasks(window)
  window.scheduler.drain_microtasks
end

#make_window(body_html = "") {|window| ... } ⇒ Dommy::Window

Build a fresh Window with the given body HTML. When a block is given, yields the window first; the same window is returned in both cases so callers can choose their style.

Parameters:

  • body_html (String) (defaults to: "")

    HTML to insert inside <body>

Yield Parameters:

Returns:



52
53
54
55
56
57
# File 'lib/dommy/test_helpers.rb', line 52

def make_window(body_html = "")
  window = Dommy::Window.new
  window.document.body.inner_html = body_html.to_s
  yield window if block_given?
  window
end

#parse_html(html = "") ⇒ Dommy::Document

Parse an HTML string into a fresh Document and return it.

When the input starts with ‘<!doctype` or `<html>`, it is parsed as a full HTML document (preserving <head>, <title>, etc.). Otherwise the input is treated as a body fragment and inserted into a fresh document’s <body>.

Parameters:

  • html (String) (defaults to: "")

    HTML to parse (full document or body fragment)

Returns:



41
42
43
# File 'lib/dommy/test_helpers.rb', line 41

def parse_html(html = "")
  Dommy.parse(html).document
end