Documentation
¶
Overview ¶
Package webtest tests HTTP handlers and Laravel applications in memory, without opening a network socket.
Create a Client with New to send requests to any http.Handler. The client preserves cookies across requests and follows same-host redirects like a browser:
func TestProfile(t *testing.T) {
client := webtest.New(t, app)
client.Post("/login", url.Values{"email": {"taylor@laravel.com"}}).
AssertRedirect("/dashboard").
AssertSee("Welcome back")
client.Get("/profile").AssertOK().AssertSee("taylor@laravel.com")
}
Every assertion on Response and JSON reports failures to the test and returns its receiver so calls can chain. Failure messages include the response status, redirect chain, body excerpt, validation errors, and error cause alongside what the assertion expected.
Index ¶
- type Client
- func (c *Client) Delete(path string) *Response
- func (c *Client) DeleteJSON(path string, body ...any) *Response
- func (c *Client) Do(request *http.Request) *Response
- func (c *Client) From(page string) *Client
- func (c *Client) Get(path string) *Response
- func (c *Client) GetJSON(path string) *Response
- func (c *Client) Head(path string) *Response
- func (c *Client) NewBrowser() *Client
- func (c *Client) Patch(path string, form url.Values) *Response
- func (c *Client) PatchBody(path, contentType string, body []byte) *Response
- func (c *Client) PatchJSON(path string, body any) *Response
- func (c *Client) Post(path string, form url.Values) *Response
- func (c *Client) PostBody(path, contentType string, body []byte) *Response
- func (c *Client) PostJSON(path string, body any) *Response
- func (c *Client) Put(path string, form url.Values) *Response
- func (c *Client) PutBody(path, contentType string, body []byte) *Response
- func (c *Client) PutJSON(path string, body any) *Response
- func (c *Client) SetCookie(name, value string)
- func (c *Client) Upload(path string, fields url.Values, files ...File) *Response
- func (c *Client) WithContext(change func(ctx context.Context) context.Context) *Client
- func (c *Client) WithCookie(name, value string) *Client
- func (c *Client) WithHeader(key, value string) *Client
- func (c *Client) WithIP(ip string) *Client
- func (c *Client) WithToken(token string) *Client
- func (c *Client) WithoutRedirects() *Client
- type File
- type JSON
- func (j *JSON) Contains(path string, item any) *JSON
- func (j *JSON) Count(path string, n int) *JSON
- func (j *JSON) CountBetween(path string, least, most int) *JSON
- func (j *JSON) Each(path string, assert func(j *JSON)) *JSON
- func (j *JSON) Equals(path string, want any) *JSON
- func (j *JSON) Etc() *JSON
- func (j *JSON) First(path string, assert func(j *JSON)) *JSON
- func (j *JSON) Has(path string) *JSON
- func (j *JSON) HasAny(paths ...string) *JSON
- func (j *JSON) Missing(path string) *JSON
- func (j *JSON) Scope(path string, assert func(j *JSON)) *JSON
- func (j *JSON) Where[T any](path string, check func(T) bool) *JSON
- type Response
- func (res *Response) AssertAccepted() *Response
- func (res *Response) AssertAuthenticated() *Response
- func (res *Response) AssertAuthenticatedAs[U any](user *U) *Response
- func (res *Response) AssertBadRequest() *Response
- func (res *Response) AssertClientError() *Response
- func (res *Response) AssertConflict() *Response
- func (res *Response) AssertCookie(name, value string) *Response
- func (res *Response) AssertCookieExpired(name string) *Response
- func (res *Response) AssertCookieMissing(name string) *Response
- func (res *Response) AssertCookiePresent(name string) *Response
- func (res *Response) AssertCreated() *Response
- func (res *Response) AssertDeferred(props ...string) *Response
- func (res *Response) AssertDeferredIn(group string, props ...string) *Response
- func (res *Response) AssertDontSee(text string) *Response
- func (res *Response) AssertDontSeeHTML(markup string) *Response
- func (res *Response) AssertDownload(name string) *Response
- func (res *Response) AssertError(target error) *Response
- func (res *Response) AssertErrorWhere[E error](check func(E) bool) *Response
- func (res *Response) AssertExactJSON(want any) *Response
- func (res *Response) AssertExactJSONStructure(structure any) *Response
- func (res *Response) AssertFailedDependency() *Response
- func (res *Response) AssertFlash(path string, want any) *Response
- func (res *Response) AssertFlashMissing(path string) *Response
- func (res *Response) AssertForbidden() *Response
- func (res *Response) AssertFound() *Response
- func (res *Response) AssertGone() *Response
- func (res *Response) AssertGuest() *Response
- func (res *Response) AssertHeader(key, value string) *Response
- func (res *Response) AssertHeaderContains(key, text string) *Response
- func (res *Response) AssertHeaderMissing(key string) *Response
- func (res *Response) AssertHeaderPresent(key string) *Response
- func (res *Response) AssertInertia(component string) *Response
- func (res *Response) AssertInertiaMatches(assert func(props *JSON)) *Response
- func (res *Response) AssertInternalServerError() *Response
- func (res *Response) AssertInvalid(fields ...string) *Response
- func (res *Response) AssertInvalidIn(bag string, fields ...string) *Response
- func (res *Response) AssertInvalidMessage(field, text string) *Response
- func (res *Response) AssertInvalidMessageIn(bag, field, text string) *Response
- func (res *Response) AssertJSON(want any) *Response
- func (res *Response) AssertJSONCount(path string, n int) *Response
- func (res *Response) AssertJSONFragment(fragment any) *Response
- func (res *Response) AssertJSONMatches(assert func(j *JSON)) *Response
- func (res *Response) AssertJSONMissing(fragment any) *Response
- func (res *Response) AssertJSONMissingPath(path string) *Response
- func (res *Response) AssertJSONPath(path string, want any) *Response
- func (res *Response) AssertJSONPathWhere[T any](path string, check func(T) bool) *Response
- func (res *Response) AssertJSONStructure(structure any) *Response
- func (res *Response) AssertLink(rel, href string) *Response
- func (res *Response) AssertLinkMissing(rel string) *Response
- func (res *Response) AssertMeta(name, content string) *Response
- func (res *Response) AssertMetaMissing(name string) *Response
- func (res *Response) AssertMethodNotAllowed() *Response
- func (res *Response) AssertMovedPermanently() *Response
- func (res *Response) AssertNoContent() *Response
- func (res *Response) AssertNotAcceptable() *Response
- func (res *Response) AssertNotFound() *Response
- func (res *Response) AssertNotModified() *Response
- func (res *Response) AssertNotReported(target error) *Response
- func (res *Response) AssertNothingReported() *Response
- func (res *Response) AssertOK() *Response
- func (res *Response) AssertPaymentRequired() *Response
- func (res *Response) AssertPermanentRedirect() *Response
- func (res *Response) AssertProp(path string, want any) *Response
- func (res *Response) AssertPropMissing(path string) *Response
- func (res *Response) AssertRedirect(location string) *Response
- func (res *Response) AssertRedirectBack() *Response
- func (res *Response) AssertRedirectBackWithErrors(fields ...string) *Response
- func (res *Response) AssertRedirectBackWithoutErrors() *Response
- func (res *Response) AssertRedirectContains(text string) *Response
- func (res *Response) AssertRedirectToRoute(name string, params ...any) *Response
- func (res *Response) AssertRedirectToSignedRoute(name string, params ...any) *Response
- func (res *Response) AssertRenders(name string, data any) *Response
- func (res *Response) AssertReported(target error) *Response
- func (res *Response) AssertReportedWhere[E error](check func(E) bool) *Response
- func (res *Response) AssertRequestTimeout() *Response
- func (res *Response) AssertSchema(schemaType string) *Response
- func (res *Response) AssertSee(text string) *Response
- func (res *Response) AssertSeeHTML(markup string) *Response
- func (res *Response) AssertSeeInOrder(texts ...string) *Response
- func (res *Response) AssertServerError() *Response
- func (res *Response) AssertServiceUnavailable() *Response
- func (res *Response) AssertSessionHas(key string, want any) *Response
- func (res *Response) AssertSessionHasInput(key string, want any) *Response
- func (res *Response) AssertSessionMissing(key string) *Response
- func (res *Response) AssertSessionMissingInput(key string) *Response
- func (res *Response) AssertSessionPresent(key string) *Response
- func (res *Response) AssertSessionWhere[T any](key string, check func(T) bool) *Response
- func (res *Response) AssertSimilarJSON(want any) *Response
- func (res *Response) AssertStatus(status int) *Response
- func (res *Response) AssertSuccessful() *Response
- func (res *Response) AssertTemporaryRedirect() *Response
- func (res *Response) AssertTitle(title string) *Response
- func (res *Response) AssertTooManyRequests() *Response
- func (res *Response) AssertUnauthorized() *Response
- func (res *Response) AssertUnprocessable() *Response
- func (res *Response) AssertUnsupportedMediaType() *Response
- func (res *Response) AssertValid(fields ...string) *Response
- func (res *Response) AssertValidIn(bag string, fields ...string) *Response
- func (res *Response) AssertViewHas(path string, want any) *Response
- func (res *Response) AssertViewIs(name string) *Response
- func (res *Response) AssertViewMissing(path string) *Response
- func (res *Response) AssertViewPresent(path string) *Response
- func (res *Response) AssertViewWhere[T any](path string, check func(T) bool) *Response
- func (res *Response) Cookie(name string) *http.Cookie
- func (res *Response) Flash[T any](path string) T
- func (res *Response) JSON[T any]() T
- func (res *Response) LoadDeferredGroups(groups ...string) *Response
- func (res *Response) LoadDeferredProps() *Response
- func (res *Response) Prop[T any](path string) T
- func (res *Response) Reload() *Response
- func (res *Response) ReloadExcept(props ...string) *Response
- func (res *Response) ReloadOnly(props ...string) *Response
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client sends in-memory HTTP requests to an http.Handler and maintains a shared cookie jar across requests. Create one with New. Client is safe for concurrent use.
func New ¶
New returns a *Client that sends requests to handler and reports assertion failures to t.
Requests include Sec-Fetch-Site: same-origin by default so form submissions pass CSRF protection as they would from a browser. Override that header with Client.WithHeader to test cross-site requests.
func (*Client) DeleteJSON ¶
DeleteJSON sends an HTTP DELETE request to path with Accept set to application/json. When a non-nil body is passed, it is marshaled as JSON with Content-Type set to application/json, failing the test if body cannot be encoded.
func (*Client) Do ¶
Do sends a custom *http.Request to the client's handler, adding any headers and cookies configured on c that are not already present on request.
Unless created with Client.WithoutRedirects, c follows same-host redirects up to 10 times and returns the final *Response with its Redirects chain populated. It fails the test if more than 10 redirects occur. Following a 301, 302, or 303 switches the method to GET (or keeps HEAD) and drops the body; 307 and 308 preserve the method and are followed only for GET and HEAD. Redirects to another host are returned without following.
func (*Client) From ¶
From returns a copy of c that sets the Referer header to page (a path or full URL) on every request. Pair it with Response.AssertRedirectBack to test redirects back to the referring page. The returned client shares its cookie jar with c.
func (*Client) GetJSON ¶
GetJSON sends an HTTP GET request to path with Accept set to application/json.
func (*Client) NewBrowser ¶
NewBrowser returns a new *Client for the same handler with an empty cookie jar and default settings, as if opening a second browser or device in the same test. It inherits none of c's headers, cookies, or context modifiers:
laptop.Post("/login", form)
phone := laptop.NewBrowser()
phone.Post("/login", form)
func (*Client) Patch ¶
Patch sends form encoded as application/x-www-form-urlencoded in an HTTP PATCH request to path.
func (*Client) PatchBody ¶
PatchBody sends raw body bytes with the given contentType in an HTTP PATCH request to path.
func (*Client) PatchJSON ¶
PatchJSON marshals body as JSON, sets Content-Type and Accept to application/json, and sends an HTTP PATCH request to path. It fails the test if body cannot be encoded as JSON.
func (*Client) Post ¶
Post sends form encoded as application/x-www-form-urlencoded in an HTTP POST request to path.
func (*Client) PostBody ¶
PostBody sends raw body bytes with the given contentType in an HTTP POST request to path.
func (*Client) PostJSON ¶
PostJSON marshals body as JSON, sets Content-Type and Accept to application/json, and sends an HTTP POST request to path. It fails the test if body cannot be encoded as JSON.
func (*Client) Put ¶
Put sends form encoded as application/x-www-form-urlencoded in an HTTP PUT request to path.
func (*Client) PutBody ¶
PutBody sends raw body bytes with the given contentType in an HTTP PUT request to path.
func (*Client) PutJSON ¶
PutJSON marshals body as JSON, sets Content-Type and Accept to application/json, and sends an HTTP PUT request to path. It fails the test if body cannot be encoded as JSON.
func (*Client) SetCookie ¶
SetCookie writes a cookie directly into the shared cookie jar, as if a previous response had set it. Every client derived from the same New call sends it until a response replaces or expires it. Unlike Client.WithCookie, middleware processes the cookie as if it came from a browser, so pass already-encrypted values for encrypted cookies.
func (*Client) Upload ¶
Upload sends a multipart/form-data HTTP POST request to path containing fields and files. It fails the test if encoding any file part returns an error.
func (*Client) WithContext ¶
WithContext returns a copy of c that transforms each request's context with change before dispatching it. The returned client shares its cookie jar with c.
func (*Client) WithCookie ¶
WithCookie returns a copy of c that sends cookie name with plain value on every request. Handlers read the value as given, bypassing cookie decryption middleware. The returned client still shares response-set cookies with c, so sessions carry over.
func (*Client) WithHeader ¶
WithHeader returns a copy of c that sends header key with value on every request. The returned client shares its cookie jar with c.
func (*Client) WithIP ¶
WithIP returns a copy of c whose requests originate from ip instead of the default 192.0.2.1. Pass a load balancer's address to test trusted proxies, or a client address to test Request.IP:
client.WithIP("10.0.0.1").WithHeader("X-Forwarded-For", "203.0.113.7").Get("/")
The returned client shares its cookie jar with c.
func (*Client) WithToken ¶
WithToken returns a copy of c that sends token as a Bearer token in the Authorization header. The returned client shares its cookie jar with c.
func (*Client) WithoutRedirects ¶
WithoutRedirects returns a copy of c that returns redirect responses as-is instead of following them. The returned client shares its cookie jar with c.
type File ¶
type File struct {
// Field is the multipart form field name.
Field string
// Name is the uploaded filename.
Name string
// Content holds the raw file bytes.
Content []byte
}
File describes a file to upload in a multipart form request through Client.Upload. Use FakeFile or FakeImage to generate test files.
func FakeFile ¶
FakeFile returns a File of kilobytes*1024 zero bytes for uploading under form field via Client.Upload, useful for testing file size validation rules such as max:
client.Upload("/documents", nil, webtest.FakeFile("document", "report.pdf", 6000)).
AssertInvalid("document")
Because its bytes are zeros, content-type sniffing detects no media type. To test MIME or image validation rules, upload a real file or use FakeImage. To send a generated file through package httpclient, pass its Content and Name to httpclient.AttachData.
func FakeImage ¶
FakeImage returns a valid PNG File of width by height pixels for uploading under form field via Client.Upload, useful for testing image dimension rules or image processing handlers:
client.Upload("/avatar", nil, webtest.FakeImage("avatar", "taylor.png", 640, 480)).
AssertRedirect("/profile")
FakeImage panics if name does not end with .png (case-insensitive) or if PNG encoding fails.
type JSON ¶
type JSON struct {
// contains filtered or unexported fields
}
JSON provides fluent assertions over a decoded JSON value passed to Response.AssertJSONMatches or Response.AssertInertiaMatches. Every assertion reports failures on the test and returns j for chaining:
client.GetJSON("/api/users").AssertJSONMatches(func(j *webtest.JSON) {
j.Count("data", 2).
First("data", func(user *webtest.JSON) { user.Equals("name", "Taylor").Missing("password").Etc() }).
Each("data", func(user *webtest.JSON) { user.Where("id", func(id int) bool { return id > 0 }).Etc() }).
Scope("meta", func(meta *webtest.JSON) { meta.Equals("total", 2) })
})
Paths use dot notation such as "data.0.name", with array indexes starting at 0. Inside JSON.Scope, JSON.First, and JSON.Each, paths are relative to the scoped value, and "" refers to that value itself.
Each callback must inspect every key of its object or list, or call JSON.Etc to allow unchecked keys. Any assertion marks the top-level key of its path as checked.
func (*JSON) Contains ¶
Contains fails the test unless the array or object at path contains an element or value equal to item (normalized through JSON encoding), and returns j for chaining.
func (*JSON) Count ¶
Count fails the test unless the array or object at path has exactly n items, and returns j for chaining.
func (*JSON) CountBetween ¶
CountBetween fails the test unless the array or object at path has between least and most items inclusive, and returns j for chaining.
func (*JSON) Each ¶
Each runs assert against every item of the array or object at path, failing if it is empty, and returns j for chaining. The callback must check every key of each item or call JSON.Etc.
func (*JSON) Equals ¶
Equals fails the test unless the value at path equals want after normalizing want through JSON encoding, and returns j for chaining. Object key order is ignored, while array element order must match.
func (*JSON) First ¶
First runs assert against the first item of the array or object at path (the lowest-sorting key for an object), failing if it is empty, and returns j for chaining. The callback must check every key of that item or call JSON.Etc.
func (*JSON) Has ¶
Has fails the test unless path exists (including when its value is null), and returns j for chaining.
func (*JSON) HasAny ¶
HasAny fails the test unless at least one of paths exists, and returns j for chaining.
func (*JSON) Missing ¶
Missing fails the test if path exists (a JSON null counts as present), and returns j for chaining.
func (*JSON) Scope ¶
Scope runs assert against the array or object at path with relative paths, and returns j for chaining. The callback must check every key of the scoped value or call JSON.Etc.
func (*JSON) Where ¶
Where fails the test unless the value at path decodes into type T and satisfies check, and returns j for chaining. Return true from check to assert only the value's type:
j.Where("age", func(age int) bool { return age >= 18 })
j.Where("nickname", func(*string) bool { return true })
type Response ¶
type Response struct {
// Status is the HTTP status code of the final response.
Status int
// Header holds the response headers.
Header http.Header
// Body is the full response body as a string.
Body string
// Request is the [*web.Request] captured by the application (including its
// route and session), or nil when testing a plain [http.Handler].
Request *web.Request
// Cause is the error from which this response was rendered (such as an error
// passed to [web.Fail]), or nil.
Cause error
// Reported holds all errors reported during this request in order,
// including unhandled server errors and errors passed to Request.Report.
Reported []error
// Redirects holds each redirect response the client followed to reach this
// response, in order, starting with the response to the initial request.
Redirects []*Response
// contains filtered or unexported fields
}
Response holds the HTTP response returned by a handler along with any redirects followed to reach it. Assertion methods report failures on the test and return res for chaining.
func (*Response) AssertAccepted ¶
AssertAccepted fails the test unless the response status is 202 Accepted, and returns res for chaining.
func (*Response) AssertAuthenticated ¶
AssertAuthenticated fails the test unless a user is signed in to the session after the initial request finishes (for example, after submitting a login form), and returns res for chaining. Because laraveltest's ActingAs does not write to the session, its requests pass only if the handler signs a user in.
func (*Response) AssertAuthenticatedAs ¶
AssertAuthenticatedAs fails the test unless user is signed in to the session after the initial request finishes, comparing user's ID field against the user ID stored in the session, and returns res for chaining:
client.Post("/login", form).AssertAuthenticatedAs(&user)
It fails the test immediately if type U has no exported ID field.
func (*Response) AssertBadRequest ¶
AssertBadRequest fails the test unless the response status is 400 Bad Request, and returns res for chaining.
func (*Response) AssertClientError ¶
AssertClientError fails the test unless the response has any 4xx status code, and returns res for chaining.
func (*Response) AssertConflict ¶
AssertConflict fails the test unless the response status is 409 Conflict, and returns res for chaining.
func (*Response) AssertCookie ¶
AssertCookie fails the test unless the response (or a followed redirect) sets cookie name to value (comparing the decrypted value when encrypted), and returns res for chaining.
func (*Response) AssertCookieExpired ¶
AssertCookieExpired fails the test unless the response (or a followed redirect) expires cookie name, and returns res for chaining.
func (*Response) AssertCookieMissing ¶
AssertCookieMissing fails the test if the response (or a followed redirect) sets or expires cookie name, and returns res for chaining.
func (*Response) AssertCookiePresent ¶
AssertCookiePresent fails the test unless the response (or a followed redirect) sets cookie name to any non-expired value, and returns res for chaining.
func (*Response) AssertCreated ¶
AssertCreated fails the test unless the response status is 201 Created, and returns res for chaining.
func (*Response) AssertDeferred ¶
AssertDeferred fails the test unless every prop in props is listed in the Inertia page's deferred props (configured with inertia.Defer), and returns res for chaining.
func (*Response) AssertDeferredIn ¶
AssertDeferredIn fails the test unless every prop in props is deferred in the named Inertia deferred group, and returns res for chaining:
client.Get("/dashboard").AssertDeferredIn("sidebar", "teams", "projects")
func (*Response) AssertDontSee ¶
AssertDontSee fails the test if the response body contains text either literally or as escaped by html/template, and returns res for chaining.
func (*Response) AssertDontSeeHTML ¶
AssertDontSeeHTML fails the test if the response body contains markup verbatim, and returns res for chaining.
func (*Response) AssertDownload ¶
AssertDownload fails the test unless the response sends a file attachment named name (as web.Download and web.StreamDownload do via Content-Disposition), and returns res for chaining.
func (*Response) AssertError ¶
AssertError fails the test unless res or a redirect followed to reach it was rendered from an error matching target according to errors.Is, and returns res for chaining:
client.Post("/checkout", form).AssertStatus(402).AssertError(billing.ErrCardDeclined)
To match by error type and inspect fields, use Response.AssertErrorWhere or call errors.AsType on Cause.
func (*Response) AssertErrorWhere ¶
AssertErrorWhere fails the test unless res or a redirect followed to reach it was rendered from an error matching type E via errors.AsType that satisfies check, and returns res for chaining:
res.AssertErrorWhere(func(err *billing.DeclinedError) bool { return err.Reason == "insufficient funds" })
func (*Response) AssertExactJSON ¶
AssertExactJSON fails the test unless the response body is JSON equal to want with no extra keys or array items and with arrays in the same order, and returns res for chaining. Key order and number formatting are ignored.
func (*Response) AssertExactJSONStructure ¶
AssertExactJSONStructure fails the test unless the JSON body matches structure, like Response.AssertJSONStructure, with no extra keys, and returns res for chaining.
func (*Response) AssertFailedDependency ¶
AssertFailedDependency fails the test unless the response status is 424 Failed Dependency, and returns res for chaining.
func (*Response) AssertFlash ¶
AssertFlash fails the test unless the Inertia page carries flash data (set via inertia.Flash) at dot path (such as "toast") equal to want after normalizing want through JSON encoding, and returns res for chaining.
func (*Response) AssertFlashMissing ¶
AssertFlashMissing fails the test if the Inertia page carries flash data at dot path, and returns res for chaining.
func (*Response) AssertForbidden ¶
AssertForbidden fails the test unless the response status is 403 Forbidden, and returns res for chaining.
func (*Response) AssertFound ¶
AssertFound fails the test unless the response status is 302 Found (the status returned by web.Redirect), and returns res for chaining.
func (*Response) AssertGone ¶
AssertGone fails the test unless the response status is 410 Gone, and returns res for chaining.
func (*Response) AssertGuest ¶
AssertGuest fails the test if any user is signed in to the session after the initial request finishes (for example, after logging out or a failed login), and returns res for chaining.
func (*Response) AssertHeader ¶
AssertHeader fails the test unless header key equals value, and returns res for chaining.
func (*Response) AssertHeaderContains ¶
AssertHeaderContains fails the test unless header key's value contains text (such as "charset=utf-8" in Content-Type), and returns res for chaining.
func (*Response) AssertHeaderMissing ¶
AssertHeaderMissing fails the test if header key is present on the response, and returns res for chaining.
func (*Response) AssertHeaderPresent ¶
AssertHeaderPresent fails the test unless header key is present on the response with any value, and returns res for chaining.
func (*Response) AssertInertia ¶
AssertInertia fails the test unless the response is an Inertia page for component (such as "Users/Show"), and returns res for chaining. When the application has a resources/js/pages directory, AssertInertia also verifies that a matching component file exists there (such as Users/Show.tsx) so misspelled component names fail the test.
func (*Response) AssertInertiaMatches ¶
AssertInertiaMatches inspects the Inertia page's props with a fluent *JSON assertion callback (just as Response.AssertJSONMatches inspects a JSON body), and returns res for chaining:
client.Get("/users").AssertInertia("Users/Index").AssertInertiaMatches(func(props *webtest.JSON) {
props.Count("users", 3).
First("users", func(user *webtest.JSON) { user.Equals("name", "Taylor").Missing("password").Etc() })
})
Top-level props may be left unchecked so shared props and errors do not need to be listed, while callbacks passed to JSON.Scope, JSON.First, and JSON.Each must check every key of their value or call JSON.Etc.
func (*Response) AssertInternalServerError ¶
AssertInternalServerError fails the test unless the response status is 500 Internal Server Error, and returns res for chaining.
func (*Response) AssertInvalid ¶
AssertInvalid fails the test unless validation failed with at least one error for each field in fields, and returns res for chaining. It reads errors from a 422 JSON response body or from the default session error bag flashed on a redirect.
func (*Response) AssertInvalidIn ¶
AssertInvalidIn behaves like Response.AssertInvalid for forms that store errors in a named session error bag via r.ValidateIn, and returns res for chaining. For 422 JSON responses (which do not name a bag), it checks the JSON errors directly.
func (*Response) AssertInvalidMessage ¶
AssertInvalidMessage fails the test unless validation failed with an error for field whose message contains text (from a 422 JSON response or the default session error bag), and returns res for chaining.
func (*Response) AssertInvalidMessageIn ¶
AssertInvalidMessageIn behaves like Response.AssertInvalidMessage for a named session error bag created with r.ValidateIn, and returns res for chaining.
func (*Response) AssertJSON ¶
AssertJSON fails the test unless the response body is JSON containing want (any value that encodes to JSON, such as a struct or map), and returns res for chaining. Objects may include additional keys not listed in want, and arrays may include additional trailing items:
client.GetJSON("/api/users").AssertJSON(map[string]any{
"data": []any{map[string]any{"name": "Taylor"}, map[string]any{"name": "Abigail"}},
})
Key order and number formatting are ignored. For strict equality with no extra keys or items, use Response.AssertExactJSON.
func (*Response) AssertJSONCount ¶
AssertJSONCount fails the test unless the JSON array or object at dot path has exactly n items, and returns res for chaining. Pass "" to count the root value itself:
client.GetJSON("/api/users").AssertJSONCount("data", 3)
func (*Response) AssertJSONFragment ¶
AssertJSONFragment fails the test unless fragment appears anywhere within the JSON body (matched by containment, as in Response.AssertJSON), and returns res for chaining:
res.AssertJSONFragment(map[string]any{"name": "Taylor", "role": "admin"})
func (*Response) AssertJSONMatches ¶
AssertJSONMatches inspects the JSON response body with a fluent *JSON callback and returns res for chaining:
client.GetJSON("/api/users/1").AssertJSONMatches(func(j *webtest.JSON) {
j.Equals("id", 1).
Equals("name", "Taylor").
Missing("password").
Scope("team", func(team *webtest.JSON) { team.Has("id").Etc() })
})
The callback must check every top-level key of the body or call JSON.Etc, ensuring tests catch unexpected fields such as leaked sensitive attributes.
func (*Response) AssertJSONMissing ¶
AssertJSONMissing fails the test if fragment appears anywhere within the JSON body (matched as in Response.AssertJSONFragment), and returns res for chaining.
func (*Response) AssertJSONMissingPath ¶
AssertJSONMissingPath fails the test if the JSON body has a value at dot path (a JSON null counts as present), and returns res for chaining.
func (*Response) AssertJSONPath ¶
AssertJSONPath fails the test unless the JSON value at dot path (such as "data.0.name") equals want after normalizing want through JSON encoding, and returns res for chaining.
func (*Response) AssertJSONPathWhere ¶
AssertJSONPathWhere fails the test unless the JSON value at dot path decodes into type T and satisfies check, and returns res for chaining:
res.AssertJSONPathWhere("meta.total", func(total int) bool { return total > 10 })
func (*Response) AssertJSONStructure ¶
AssertJSONStructure fails the test unless the JSON body contains all keys described by structure regardless of their values, and returns res for chaining. Slices list required key names, maps associate keys with nested structures, and "*" applies a nested structure to every element of an array or object:
res.AssertJSONStructure(map[string]any{
"data": map[string]any{"*": []any{"id", "name", map[string]any{"team": []any{"id", "name"}}}},
"meta": []any{"total"},
})
func (*Response) AssertLink ¶
AssertLink fails the test unless the page's head contains a <link> tag with matching rel and href attributes (such as "canonical" and "https://example.com/posts/1"), and returns res for chaining.
func (*Response) AssertLinkMissing ¶
AssertLinkMissing fails the test if the page's head contains any <link> tag with the given rel attribute, and returns res for chaining.
func (*Response) AssertMeta ¶
AssertMeta fails the test unless the page's head contains a single <meta> tag whose name or property equals name and whose content equals content (such as "description" or "og:title"), and returns res for chaining.
func (*Response) AssertMetaMissing ¶
AssertMetaMissing fails the test if the page's head contains any <meta> tag whose name or property equals name (such as "robots"), and returns res for chaining.
func (*Response) AssertMethodNotAllowed ¶
AssertMethodNotAllowed fails the test unless the response status is 405 Method Not Allowed, and returns res for chaining.
func (*Response) AssertMovedPermanently ¶
AssertMovedPermanently fails the test unless the response status is 301 Moved Permanently, and returns res for chaining.
func (*Response) AssertNoContent ¶
AssertNoContent fails the test unless the response status is 204 No Content with an empty body, and returns res for chaining.
func (*Response) AssertNotAcceptable ¶
AssertNotAcceptable fails the test unless the response status is 406 Not Acceptable, and returns res for chaining.
func (*Response) AssertNotFound ¶
AssertNotFound fails the test unless the response status is 404 Not Found, and returns res for chaining.
func (*Response) AssertNotModified ¶
AssertNotModified fails the test unless the response status is 304 Not Modified, and returns res for chaining.
func (*Response) AssertNotReported ¶
AssertNotReported fails the test if the request or any redirect followed to reach it reported an error matching target according to errors.Is, and returns res for chaining. Unrelated reported errors are allowed.
func (*Response) AssertNothingReported ¶
AssertNothingReported fails the test if the request or any redirect followed to reach it reported any error, and returns res for chaining.
func (*Response) AssertOK ¶
AssertOK fails the test unless the response status is 200 OK, and returns res for chaining.
func (*Response) AssertPaymentRequired ¶
AssertPaymentRequired fails the test unless the response status is 402 Payment Required, and returns res for chaining.
func (*Response) AssertPermanentRedirect ¶
AssertPermanentRedirect fails the test unless the response status is 308 Permanent Redirect, and returns res for chaining.
func (*Response) AssertProp ¶
AssertProp fails the test unless the Inertia page has a prop at dot path (such as "user.name") equal to want after normalizing want through JSON encoding, and returns res for chaining. On pages with PreserveBigIntegers enabled, preserved big integers compare as exact integers rather than raw {"$bigint": ...} markers.
func (*Response) AssertPropMissing ¶
AssertPropMissing fails the test if the Inertia page has a prop at dot path (such as a deferred prop on the initial visit), and returns res for chaining.
func (*Response) AssertRedirect ¶
AssertRedirect fails the test unless the initial request redirected to location (a path such as "/dashboard" or a full URL), and returns res for chaining. A path matches redirects to that path on any host. Because res is the final response after following redirects, subsequent chained assertions inspect the destination page.
func (*Response) AssertRedirectBack ¶
AssertRedirectBack fails the test unless the initial request redirected back to its Referer URL (as web.Back does), and returns res for chaining. Send the request with Client.From to set the referring page:
client.From("/profile/edit").Post("/profile", form).AssertRedirectBack()
func (*Response) AssertRedirectBackWithErrors ¶
AssertRedirectBackWithErrors combines Response.AssertRedirectBack and Response.AssertInvalid for fields, and returns res for chaining.
func (*Response) AssertRedirectBackWithoutErrors ¶
AssertRedirectBackWithoutErrors combines Response.AssertRedirectBack and Response.AssertValid, and returns res for chaining.
func (*Response) AssertRedirectContains ¶
AssertRedirectContains fails the test unless the initial request redirected to a Location header containing text (such as a query parameter), and returns res for chaining.
func (*Response) AssertRedirectToRoute ¶
AssertRedirectToRoute fails the test unless the initial request redirected to the URL of named route name formatted with params via urls.Route, and returns res for chaining:
client.Post("/posts", form).AssertRedirectToRoute("posts.show", "post", 1)
func (*Response) AssertRedirectToSignedRoute ¶
AssertRedirectToSignedRoute fails the test unless the initial request redirected to a valid, unexpired signed URL for named route name with params (created by urls.SignedRoute or urls.TemporarySignedRoute), and returns res for chaining.
func (*Response) AssertRenders ¶
AssertRenders fails the test unless the response body matches view name rendered with data in the same request context, helpers, and fragments, and returns res for chaining:
client.Get("/posts/1").AssertRenders("posts.show", post)
func (*Response) AssertReported ¶
AssertReported fails the test unless the request or a redirect followed to reach it reported an error matching target according to errors.Is (including errors passed to Request.Report), and returns res for chaining.
func (*Response) AssertReportedWhere ¶
AssertReportedWhere fails the test unless the request or a redirect followed to reach it reported an error matching type E via errors.AsType that satisfies check, and returns res for chaining:
res.AssertReportedWhere(func(err *httpclient.StatusError) bool { return err.Response.Status == 502 })
func (*Response) AssertRequestTimeout ¶
AssertRequestTimeout fails the test unless the response status is 408 Request Timeout, and returns res for chaining.
func (*Response) AssertSchema ¶
AssertSchema fails the test unless the page's head contains a JSON-LD <script type="application/ld+json"> block whose @type equals schemaType (such as "Product"), and returns res for chaining.
func (*Response) AssertSee ¶
AssertSee fails the test unless the response body contains text either literally or as escaped by html/template (so "O'Brien" matches HTML-escaped output), and returns res for chaining.
func (*Response) AssertSeeHTML ¶
AssertSeeHTML fails the test unless the response body contains markup verbatim, without HTML-escaping it, and returns res for chaining.
func (*Response) AssertSeeInOrder ¶
AssertSeeInOrder fails the test unless the response body contains every string in texts in order (each matched literally or as escaped by html/template, like Response.AssertSee), and returns res for chaining.
func (*Response) AssertServerError ¶
AssertServerError fails the test unless the response has any 5xx status code, and returns res for chaining. To assert specifically on 500 Internal Server Error, use Response.AssertInternalServerError.
func (*Response) AssertServiceUnavailable ¶
AssertServiceUnavailable fails the test unless the response status is 503 Service Unavailable, and returns res for chaining.
func (*Response) AssertSessionHas ¶
AssertSessionHas fails the test unless the session contains want at key after the initial request finishes (including flash data for the next request), and returns res for chaining.
func (*Response) AssertSessionHasInput ¶
AssertSessionHasInput fails the test unless the initial request flashed old form input at dot path key equal to want (for example, after validation failure or Session.FlashInput), and returns res for chaining:
client.Post("/sign-up", form).
AssertSessionHasInput("email", "taylor@laravel.com").
AssertSessionMissingInput("password")
func (*Response) AssertSessionMissing ¶
AssertSessionMissing fails the test if the session contains any entry at key after the initial request finishes, and returns res for chaining.
func (*Response) AssertSessionMissingInput ¶
AssertSessionMissingInput fails the test if the initial request flashed old form input at dot path key (such as a password field), and returns res for chaining.
func (*Response) AssertSessionPresent ¶
AssertSessionPresent fails the test unless the session contains a non-nil value at key after the initial request finishes (including flash data), and returns res for chaining.
func (*Response) AssertSessionWhere ¶
AssertSessionWhere fails the test unless the session value at key decodes into type T (as the next request would read it back) and satisfies check, and returns res for chaining:
res.AssertSessionWhere("cart.items", func(items []int) bool { return slices.Contains(items, 7) })
func (*Response) AssertSimilarJSON ¶
AssertSimilarJSON fails the test unless the response body is JSON equal to want, like Response.AssertExactJSON, except array element order is ignored, and returns res for chaining.
func (*Response) AssertStatus ¶
AssertStatus fails the test unless the final response has HTTP status code status, and returns res for chaining. To assert on a redirect response, use Response.AssertRedirect or send the request with Client.WithoutRedirects.
func (*Response) AssertSuccessful ¶
AssertSuccessful fails the test unless the response has any 2xx status code, and returns res for chaining.
func (*Response) AssertTemporaryRedirect ¶
AssertTemporaryRedirect fails the test unless the response status is 307 Temporary Redirect, and returns res for chaining.
func (*Response) AssertTitle ¶
AssertTitle fails the test unless the page's head contains exactly one <title> element with text equal to title, and returns res for chaining. It inspects the <head> of an HTML response or the head prop of an Inertia visit.
func (*Response) AssertTooManyRequests ¶
AssertTooManyRequests fails the test unless the response status is 429 Too Many Requests, and returns res for chaining.
func (*Response) AssertUnauthorized ¶
AssertUnauthorized fails the test unless the response status is 401 Unauthorized, and returns res for chaining.
func (*Response) AssertUnprocessable ¶
AssertUnprocessable fails the test unless the response status is 422 Unprocessable Entity, and returns res for chaining.
func (*Response) AssertUnsupportedMediaType ¶
AssertUnsupportedMediaType fails the test unless the response status is 415 Unsupported Media Type, and returns res for chaining.
func (*Response) AssertValid ¶
AssertValid fails the test if validation reported errors in the default error bag (or in a 422 JSON response), and returns res for chaining. When fields are given, it checks only that none of those fields has an error; when omitted, it asserts that there are no validation errors at all. For a named error bag, use Response.AssertValidIn.
func (*Response) AssertValidIn ¶
AssertValidIn behaves like Response.AssertValid for a named session error bag created with r.ValidateIn, and returns res for chaining.
func (*Response) AssertViewHas ¶
AssertViewHas fails the test unless the view data at dot path (resolving map keys, exported struct fields, zero-argument exported methods, and slice indexes such as "Post.Title", "Conferences.Items.0.Name", or "posts.0.Title") equals want after normalizing both through JSON encoding, and returns res for chaining:
client.Get("/posts/1").AssertViewIs("posts.show").AssertViewHas("Title", "Hello")
func (*Response) AssertViewIs ¶
AssertViewIs fails the test unless the response rendered the view named name (such as "posts.show"), and returns res for chaining.
func (*Response) AssertViewMissing ¶
AssertViewMissing fails the test if the view data contains a value at dot path (resolved as in Response.AssertViewHas), and returns res for chaining.
func (*Response) AssertViewPresent ¶
AssertViewPresent fails the test unless the view data contains a value at dot path (resolved as in Response.AssertViewHas), and returns res for chaining.
func (*Response) AssertViewWhere ¶
AssertViewWhere fails the test unless the view data at dot path (resolved as in Response.AssertViewHas) has concrete type T and satisfies check, and returns res for chaining. Pass "" to inspect the root view data value:
res.AssertViewWhere("Posts", func(posts []models.Post) bool { return len(posts) == 3 })
func (*Response) Cookie ¶
Cookie returns the last *http.Cookie set under name by res or any redirect followed to reach it, or nil if none was set. Its Value is unescaped and decrypted automatically when the route encrypts cookies.
func (*Response) Flash ¶
Flash decodes the Inertia page's flash data (set via inertia.Flash) at dot path as T, similar to Response.Prop. Use it when the test needs a flashed value such as a one-time API token:
token := client.Post("/profile/token", nil).Flash[string]("token")
Flash stops the test immediately if the response is not an Inertia page, the flash key is missing, or decoding as T fails.
func (*Response) JSON ¶
JSON unmarshals the response body as T. It stops the test immediately if the body cannot be decoded as T:
post := client.Get("/api/posts/1").AssertOK().JSON[Post]()
func (*Response) LoadDeferredGroups ¶
LoadDeferredGroups sends an Inertia partial reload request for the props in the named deferred groups and returns the new *Response:
client.Get("/dashboard").LoadDeferredGroups("sidebar").AssertProp("teams.0.name", "Laravel")
It stops the test immediately if res is not an Inertia page or if any group is not declared on the page.
func (*Response) LoadDeferredProps ¶
LoadDeferredProps sends an Inertia partial reload request for every deferred prop declared on the page and returns the new *Response:
client.Get("/dashboard").AssertPropMissing("stats").
LoadDeferredProps().AssertProp("stats.visits", 42)
It stops the test immediately if res is not an Inertia page.
func (*Response) Prop ¶
Prop decodes the Inertia page's prop at dot path as T, similar to Response.JSON. Use it when the test needs a prop value for a later step, such as a URL to visit:
link := client.Get("/events/7").Prop[string]("inviteLink")
Prop stops the test immediately if the response is not an Inertia page, the prop is missing, or decoding as T fails.
func (*Response) Reload ¶
Reload sends a full Inertia visit to the current page's URL and returns the new *Response:
client.Get("/dashboard").AssertProp("visits", 1).Reload().AssertProp("visits", 2)
It stops the test immediately if res is not an Inertia page.
func (*Response) ReloadExcept ¶
ReloadExcept sends an Inertia partial reload request excluding props (via X-Inertia-Partial-Except) and returns the new *Response. It stops the test immediately if res is not an Inertia page.
func (*Response) ReloadOnly ¶
ReloadOnly sends an Inertia partial reload request asking only for props (via X-Inertia-Partial-Data) and returns the new *Response:
client.Get("/users/1").AssertDeferred("activity").
ReloadOnly("activity").AssertProp("activity.0.title", "Signed in")
It stops the test immediately if res is not an Inertia page.