Litewire 1.1.0 ยท Reference

Testing

Test the fragment contract on the server and the interaction in a real browser. Litewire has no test mode; use your existing PHP or Node.js runner and a browser automation tool.

Litewire depends on fetch, history, MutationObserver, and the DOM. A browser test covers the swap, URL, and cleanup paths that a server-only or DOM-emulator test misses. Keep the server fragment and the browser behavior as separate test layers.

What to test at each layer

LayerAssertions
Server fragmentStatus is 2xx; the body is the fragment, not a layout; required IDs and attributes are present; user values are escaped; unauthorized and invalid requests are rejected.
Browser interactionThe target changes; the page did not reload; swap modes and out-of-band updates land correctly; history and back/forward work; loading classes are removed.
Client APIThe loaded version is the one you expect; plugins register once; stores keep their identity; expression mode matches the deployment.

A non-2xx response is a request failure: Litewire does not insert its body. If users must see an error message, return 200 with an error fragment, or render the message from a litewire:error listener.


Test the server fragment contract

Use the same client markup in both backends. The test asserts the response that Litewire will insert, without booting a browser.

Shared client markup

<button
 type="button"
 lw-get="/products/42/card"
 lw-target="#product-42"
 lw-swap="innerHTML"
>
 Load product
</button>
<section id="product-42" aria-live="polite"></section>

1. Route

// app/Routes/web.php
Route::get('/products/{id}/card', 'ProductController@card')
 ->whereNumber('id')
 ->name('products.card');

2. Controller action

// app/Controllers/ProductController.php
public function card(int $id): Response
{
 $product = Product::find($id);

 if ($product === null) {
 return $this->html('Product not found.', 404);
 }

 return $this->view('fragments.products.card', data: [
 'product' => $product,
 ]);
}

3. Fragment view

<!-- app/Views/fragments/products/card.blade.php -->
<article data-product-id="{{ $product->id }}">
 <h2 class="h5">{{ $product->name }}</h2>
 <p class="mb-0">${{ number_format($product->price, 2) }}</p>
</article>
import test from "node:test";
import assert from "node:assert/strict";
import request from "supertest";
import { app } from "../app.js";

test("returns only the product card fragment", async () => {
 const response = await request(app)
 .get("/products/42/card")
 .set("Accept", "text/html");

 assert.equal(response.status, 200);
 assert.match(response.headers["content-type"], /text\/html/);
 assert.match(response.text, /data-product-id="42"/);
 assert.doesNotMatch(response.text, /<nav/);
});

Run it with node --test tests/product-card.test.js. Install the HTTP helper with npm install --save-dev supertest and export the Express app from app.js.

Also cover the failure path


Test the interaction in a browser

Use Playwright, Cypress, or another real-browser runner. Start the app with its normal server, then assert the target content and the URL. The examples below use Playwright:

npm install --save-dev @playwright/test
npx playwright install

Swap without a full page load

import { test, expect } from "@playwright/test";

test("loads a product card without reloading the page", async ({ page }) => {
 await page.goto("/products");
 await page.evaluate(() => {
 window.__litewireTestPage = "same-document";
 });

 await page.getByRole("button", { name: "Load product" }).click();

 await expect(
 page.locator("#product-42 [data-product-id='42']")
 ).toBeVisible();
 await expect(page.locator("#product-42")).toContainText("Field notebook");

 expect(await page.evaluate(() => window.__litewireTestPage))
 .toBe("same-document");
});

The marker is cleared by a full navigation, so it fails if the click submits or follows a link instead of using Litewire.

History, back, and restoration

test("pushes list history and restores it on back", async ({ page }) => {
 await page.goto("/products");

 await page.getByRole("button", { name: "Next page" }).click();
 await expect(page).toHaveURL(/page=2/);
 await expect(page.locator("#product-list")).toContainText("Page 2");

 await page.goBack();
 await expect(page).toHaveURL(/\/products$/);
 await expect(page.locator("#product-list")).not.toContainText("Page 2");
});

The second test assumes your markup uses lw-push-url. See Swaps & history for the history contract.


Test the client API in the same browser

A loaded page is already a realistic environment for the JavaScript API. Evaluate against window.litewire instead of building a separate DOM shim.

test("creates one reactive store per name", async ({ page }) => {
 await page.goto("/");

 const result = await page.evaluate(() => {
 const first = window.litewire.store("cart", { items: [] });
 const second = window.litewire.store("cart", { items: ["other"] });

 return {
 sameObject: first === second,
 itemCount: second.items.length,
 version: window.litewire.constructor.version,
 };
 });

 expect(result.sameObject).toBe(true);
 expect(result.itemCount).toBe(0);
 expect(result.version).toBe("1.1.0");
});

The second store() call returns the existing store and does not reset it. Pinning version makes a dependency upgrade show up as a test failure. The full API is in Public API.


Test failure and edge paths

CaseWhat to assert
Non-2xx responseThe target is unchanged and litewire:error fires.
Timeoutlitewire:timeout fires, the request is cancelled, and loading classes are removed.
Missing OOB targetlitewire:oobError reports the selector; the main swap still completes.
Cross-origin history URLlitewire:historyError fires and the page URL does not change.
RetryA retryable status is attempted again; a non-retryable status is not. Do not retry non-idempotent writes without server support.

Capture events with a listener before the action, then assert the recorded detail. Do not sleep for a fixed time; wait for the target or the event.


Keep tests deterministic