Testing
Test components with go test: render them to HTML, mount them in a test engine, and match their trees.
This page covers testing components with plain
go test
, without a browser: rendering to HTML, the
TestEngine
that mounts components and runs their queued work, and
Match
, which compares a rendered tree with an expected one. Tests run on the server side of the
app
package, so the last sections cover what behaves differently there.
The examples test this component:
type
greeting
struct
{
app
.
Compo
Name
string
}
func
(
g
*
greeting
)
Render
(
)
app
.
UI
{
return
app
.
Div
(
)
.
Class
(
"greeting"
)
.
Body
(
app
.
H1
(
)
.
Text
(
"Hello, "
+
g
.
Name
)
,
)
}
ยง1 Rendering to HTML
func
HTMLString
(
ui
UI
)
string
func
PrintHTML
(
w
io
.
Writer
,
ui
UI
)
-
HTMLStringrendersuito HTML with a fresh test engine. Components are rendered by callingRender, but nothing is mounted and no lifecycle hook runs, so what you see is the tree built from the fields as they are. - The output is indented: each element on its own line, nested two spaces per level. Assert on substrings that stay on one line, or strip the indentation first.
-
Event handlers do not appear in the HTML. A rule passed to
Style(rule)appears as its class name in theclassattribute. -
PrintHTMLwrites the same text tow.
func
TestGreetingRenders
(
t
*
testing
.
T
)
{
out
:=
app
.
HTMLString
(
&
greeting
{
Name
:
"Ada"
}
)
if
!
strings
.
Contains
(
out
,
"<h1>Hello, Ada</h1>"
)
{
t
.
Errorf
(
"unexpected HTML: %s"
,
out
)
}
}
This is the quickest test, and often enough: render a component with given fields and check what it shows.