webtest

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 36 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

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

func New(t testing.TB, handler http.Handler) *Client

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) Delete

func (c *Client) Delete(path string) *Response

Delete sends an HTTP DELETE request to path.

func (*Client) DeleteJSON

func (c *Client) DeleteJSON(path string, body ...any) *Response

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

func (c *Client) Do(request *http.Request) *Response

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

func (c *Client) From(page string) *Client

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) Get

func (c *Client) Get(path string) *Response

Get sends an HTTP GET request to path.

func (*Client) GetJSON

func (c *Client) GetJSON(path string) *Response

GetJSON sends an HTTP GET request to path with Accept set to application/json.

func (*Client) Head

func (c *Client) Head(path string) *Response

Head sends an HTTP HEAD request to path.

func (*Client) NewBrowser

func (c *Client) NewBrowser() *Client

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

func (c *Client) Patch(path string, form url.Values) *Response

Patch sends form encoded as application/x-www-form-urlencoded in an HTTP PATCH request to path.

func (*Client) PatchBody

func (c *Client) PatchBody(path, contentType string, body []byte) *Response

PatchBody sends raw body bytes with the given contentType in an HTTP PATCH request to path.

func (*Client) PatchJSON

func (c *Client) PatchJSON(path string, body any) *Response

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

func (c *Client) Post(path string, form url.Values) *Response

Post sends form encoded as application/x-www-form-urlencoded in an HTTP POST request to path.

func (*Client) PostBody

func (c *Client) PostBody(path, contentType string, body []byte) *Response

PostBody sends raw body bytes with the given contentType in an HTTP POST request to path.

func (*Client) PostJSON

func (c *Client) PostJSON(path string, body any) *Response

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

func (c *Client) Put(path string, form url.Values) *Response

Put sends form encoded as application/x-www-form-urlencoded in an HTTP PUT request to path.

func (*Client) PutBody

func (c *Client) PutBody(path, contentType string, body []byte) *Response

PutBody sends raw body bytes with the given contentType in an HTTP PUT request to path.

func (*Client) PutJSON

func (c *Client) PutJSON(path string, body any) *Response

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

func (c *Client) SetCookie(name, value string)

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

func (c *Client) Upload(path string, fields url.Values, files ...File) *Response

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

func (c *Client) WithContext(change func(ctx context.Context) context.Context) *Client

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

func (c *Client) WithCookie(name, value string) *Client

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

func (c *Client) WithHeader(key, value string) *Client

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

func (c *Client) WithIP(ip string) *Client

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

func (c *Client) WithToken(token string) *Client

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

func (c *Client) WithoutRedirects() *Client

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

func FakeFile(field, name string, kilobytes int) File

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

func FakeImage(field, name string, width, height int) File

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

func (j *JSON) Contains(path string, item any) *JSON

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

func (j *JSON) Count(path string, n int) *JSON

Count fails the test unless the array or object at path has exactly n items, and returns j for chaining.

func (*JSON) CountBetween

func (j *JSON) CountBetween(path string, least, most int) *JSON

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

func (j *JSON) Each(path string, assert func(j *JSON)) *JSON

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

func (j *JSON) Equals(path string, want any) *JSON

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) Etc

func (j *JSON) Etc() *JSON

Etc permits unchecked keys on the current JSON value and returns j for chaining.

func (*JSON) First

func (j *JSON) First(path string, assert func(j *JSON)) *JSON

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

func (j *JSON) Has(path string) *JSON

Has fails the test unless path exists (including when its value is null), and returns j for chaining.

func (*JSON) HasAny

func (j *JSON) HasAny(paths ...string) *JSON

HasAny fails the test unless at least one of paths exists, and returns j for chaining.

func (*JSON) Missing

func (j *JSON) Missing(path string) *JSON

Missing fails the test if path exists (a JSON null counts as present), and returns j for chaining.

func (*JSON) Scope

func (j *JSON) Scope(path string, assert func(j *JSON)) *JSON

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

func (j *JSON) Where[T any](path string, check func(T) bool) *JSON

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

func (res *Response) AssertAccepted() *Response

AssertAccepted fails the test unless the response status is 202 Accepted, and returns res for chaining.

func (*Response) AssertAuthenticated

func (res *Response) AssertAuthenticated() *Response

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

func (res *Response) AssertAuthenticatedAs[U any](user *U) *Response

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

func (res *Response) AssertBadRequest() *Response

AssertBadRequest fails the test unless the response status is 400 Bad Request, and returns res for chaining.

func (*Response) AssertClientError

func (res *Response) AssertClientError() *Response

AssertClientError fails the test unless the response has any 4xx status code, and returns res for chaining.

func (*Response) AssertConflict

func (res *Response) AssertConflict() *Response

AssertConflict fails the test unless the response status is 409 Conflict, and returns res for chaining.

func (*Response) AssertCookie

func (res *Response) AssertCookie(name, value string) *Response

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

func (res *Response) AssertCookieExpired(name string) *Response

AssertCookieExpired fails the test unless the response (or a followed redirect) expires cookie name, and returns res for chaining.

func (*Response) AssertCookieMissing

func (res *Response) AssertCookieMissing(name string) *Response

AssertCookieMissing fails the test if the response (or a followed redirect) sets or expires cookie name, and returns res for chaining.

func (*Response) AssertCookiePresent

func (res *Response) AssertCookiePresent(name string) *Response

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

func (res *Response) AssertCreated() *Response

AssertCreated fails the test unless the response status is 201 Created, and returns res for chaining.

func (*Response) AssertDeferred

func (res *Response) AssertDeferred(props ...string) *Response

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

func (res *Response) AssertDeferredIn(group string, props ...string) *Response

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

func (res *Response) AssertDontSee(text string) *Response

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

func (res *Response) AssertDontSeeHTML(markup string) *Response

AssertDontSeeHTML fails the test if the response body contains markup verbatim, and returns res for chaining.

func (*Response) AssertDownload

func (res *Response) AssertDownload(name string) *Response

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

func (res *Response) AssertError(target error) *Response

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

func (res *Response) AssertErrorWhere[E error](check func(E) bool) *Response

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

func (res *Response) AssertExactJSON(want any) *Response

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

func (res *Response) AssertExactJSONStructure(structure any) *Response

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

func (res *Response) AssertFailedDependency() *Response

AssertFailedDependency fails the test unless the response status is 424 Failed Dependency, and returns res for chaining.

func (*Response) AssertFlash

func (res *Response) AssertFlash(path string, want any) *Response

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

func (res *Response) AssertFlashMissing(path string) *Response

AssertFlashMissing fails the test if the Inertia page carries flash data at dot path, and returns res for chaining.

func (*Response) AssertForbidden

func (res *Response) AssertForbidden() *Response

AssertForbidden fails the test unless the response status is 403 Forbidden, and returns res for chaining.

func (*Response) AssertFound

func (res *Response) AssertFound() *Response

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

func (res *Response) AssertGone() *Response

AssertGone fails the test unless the response status is 410 Gone, and returns res for chaining.

func (*Response) AssertGuest

func (res *Response) AssertGuest() *Response

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

func (res *Response) AssertHeader(key, value string) *Response

AssertHeader fails the test unless header key equals value, and returns res for chaining.

func (*Response) AssertHeaderContains

func (res *Response) AssertHeaderContains(key, text string) *Response

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

func (res *Response) AssertHeaderMissing(key string) *Response

AssertHeaderMissing fails the test if header key is present on the response, and returns res for chaining.

func (*Response) AssertHeaderPresent

func (res *Response) AssertHeaderPresent(key string) *Response

AssertHeaderPresent fails the test unless header key is present on the response with any value, and returns res for chaining.

func (*Response) AssertInertia

func (res *Response) AssertInertia(component string) *Response

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

func (res *Response) AssertInertiaMatches(assert func(props *JSON)) *Response

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

func (res *Response) AssertInternalServerError() *Response

AssertInternalServerError fails the test unless the response status is 500 Internal Server Error, and returns res for chaining.

func (*Response) AssertInvalid

func (res *Response) AssertInvalid(fields ...string) *Response

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

func (res *Response) AssertInvalidIn(bag string, fields ...string) *Response

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

func (res *Response) AssertInvalidMessage(field, text string) *Response

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

func (res *Response) AssertInvalidMessageIn(bag, field, text string) *Response

AssertInvalidMessageIn behaves like Response.AssertInvalidMessage for a named session error bag created with r.ValidateIn, and returns res for chaining.

func (*Response) AssertJSON

func (res *Response) AssertJSON(want any) *Response

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

func (res *Response) AssertJSONCount(path string, n int) *Response

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

func (res *Response) AssertJSONFragment(fragment any) *Response

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

func (res *Response) AssertJSONMatches(assert func(j *JSON)) *Response

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

func (res *Response) AssertJSONMissing(fragment any) *Response

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

func (res *Response) AssertJSONMissingPath(path string) *Response

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

func (res *Response) AssertJSONPath(path string, want any) *Response

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

func (res *Response) AssertJSONPathWhere[T any](path string, check func(T) bool) *Response

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

func (res *Response) AssertJSONStructure(structure any) *Response

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 (res *Response) AssertLink(rel, href string) *Response

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

func (res *Response) AssertLinkMissing(rel string) *Response

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

func (res *Response) AssertMeta(name, content string) *Response

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

func (res *Response) AssertMetaMissing(name string) *Response

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

func (res *Response) AssertMethodNotAllowed() *Response

AssertMethodNotAllowed fails the test unless the response status is 405 Method Not Allowed, and returns res for chaining.

func (*Response) AssertMovedPermanently

func (res *Response) AssertMovedPermanently() *Response

AssertMovedPermanently fails the test unless the response status is 301 Moved Permanently, and returns res for chaining.

func (*Response) AssertNoContent

func (res *Response) AssertNoContent() *Response

AssertNoContent fails the test unless the response status is 204 No Content with an empty body, and returns res for chaining.

func (*Response) AssertNotAcceptable

func (res *Response) AssertNotAcceptable() *Response

AssertNotAcceptable fails the test unless the response status is 406 Not Acceptable, and returns res for chaining.

func (*Response) AssertNotFound

func (res *Response) AssertNotFound() *Response

AssertNotFound fails the test unless the response status is 404 Not Found, and returns res for chaining.

func (*Response) AssertNotModified

func (res *Response) AssertNotModified() *Response

AssertNotModified fails the test unless the response status is 304 Not Modified, and returns res for chaining.

func (*Response) AssertNotReported

func (res *Response) AssertNotReported(target error) *Response

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

func (res *Response) AssertNothingReported() *Response

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

func (res *Response) AssertOK() *Response

AssertOK fails the test unless the response status is 200 OK, and returns res for chaining.

func (*Response) AssertPaymentRequired

func (res *Response) AssertPaymentRequired() *Response

AssertPaymentRequired fails the test unless the response status is 402 Payment Required, and returns res for chaining.

func (*Response) AssertPermanentRedirect

func (res *Response) AssertPermanentRedirect() *Response

AssertPermanentRedirect fails the test unless the response status is 308 Permanent Redirect, and returns res for chaining.

func (*Response) AssertProp

func (res *Response) AssertProp(path string, want any) *Response

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

func (res *Response) AssertPropMissing(path string) *Response

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

func (res *Response) AssertRedirect(location string) *Response

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

func (res *Response) AssertRedirectBack() *Response

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

func (res *Response) AssertRedirectBackWithErrors(fields ...string) *Response

AssertRedirectBackWithErrors combines Response.AssertRedirectBack and Response.AssertInvalid for fields, and returns res for chaining.

func (*Response) AssertRedirectBackWithoutErrors

func (res *Response) AssertRedirectBackWithoutErrors() *Response

AssertRedirectBackWithoutErrors combines Response.AssertRedirectBack and Response.AssertValid, and returns res for chaining.

func (*Response) AssertRedirectContains

func (res *Response) AssertRedirectContains(text string) *Response

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

func (res *Response) AssertRedirectToRoute(name string, params ...any) *Response

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

func (res *Response) AssertRedirectToSignedRoute(name string, params ...any) *Response

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

func (res *Response) AssertRenders(name string, data any) *Response

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

func (res *Response) AssertReported(target error) *Response

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

func (res *Response) AssertReportedWhere[E error](check func(E) bool) *Response

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

func (res *Response) AssertRequestTimeout() *Response

AssertRequestTimeout fails the test unless the response status is 408 Request Timeout, and returns res for chaining.

func (*Response) AssertSchema

func (res *Response) AssertSchema(schemaType string) *Response

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

func (res *Response) AssertSee(text string) *Response

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

func (res *Response) AssertSeeHTML(markup string) *Response

AssertSeeHTML fails the test unless the response body contains markup verbatim, without HTML-escaping it, and returns res for chaining.

func (*Response) AssertSeeInOrder

func (res *Response) AssertSeeInOrder(texts ...string) *Response

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

func (res *Response) AssertServerError() *Response

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

func (res *Response) AssertServiceUnavailable() *Response

AssertServiceUnavailable fails the test unless the response status is 503 Service Unavailable, and returns res for chaining.

func (*Response) AssertSessionHas

func (res *Response) AssertSessionHas(key string, want any) *Response

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

func (res *Response) AssertSessionHasInput(key string, want any) *Response

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

func (res *Response) AssertSessionMissing(key string) *Response

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

func (res *Response) AssertSessionMissingInput(key string) *Response

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

func (res *Response) AssertSessionPresent(key string) *Response

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

func (res *Response) AssertSessionWhere[T any](key string, check func(T) bool) *Response

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

func (res *Response) AssertSimilarJSON(want any) *Response

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

func (res *Response) AssertStatus(status int) *Response

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

func (res *Response) AssertSuccessful() *Response

AssertSuccessful fails the test unless the response has any 2xx status code, and returns res for chaining.

func (*Response) AssertTemporaryRedirect

func (res *Response) AssertTemporaryRedirect() *Response

AssertTemporaryRedirect fails the test unless the response status is 307 Temporary Redirect, and returns res for chaining.

func (*Response) AssertTitle

func (res *Response) AssertTitle(title string) *Response

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

func (res *Response) AssertTooManyRequests() *Response

AssertTooManyRequests fails the test unless the response status is 429 Too Many Requests, and returns res for chaining.

func (*Response) AssertUnauthorized

func (res *Response) AssertUnauthorized() *Response

AssertUnauthorized fails the test unless the response status is 401 Unauthorized, and returns res for chaining.

func (*Response) AssertUnprocessable

func (res *Response) AssertUnprocessable() *Response

AssertUnprocessable fails the test unless the response status is 422 Unprocessable Entity, and returns res for chaining.

func (*Response) AssertUnsupportedMediaType

func (res *Response) AssertUnsupportedMediaType() *Response

AssertUnsupportedMediaType fails the test unless the response status is 415 Unsupported Media Type, and returns res for chaining.

func (*Response) AssertValid

func (res *Response) AssertValid(fields ...string) *Response

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

func (res *Response) AssertValidIn(bag string, fields ...string) *Response

AssertValidIn behaves like Response.AssertValid for a named session error bag created with r.ValidateIn, and returns res for chaining.

func (*Response) AssertViewHas

func (res *Response) AssertViewHas(path string, want any) *Response

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

func (res *Response) AssertViewIs(name string) *Response

AssertViewIs fails the test unless the response rendered the view named name (such as "posts.show"), and returns res for chaining.

func (*Response) AssertViewMissing

func (res *Response) AssertViewMissing(path string) *Response

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

func (res *Response) AssertViewPresent(path string) *Response

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

func (res *Response) AssertViewWhere[T any](path string, check func(T) bool) *Response

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

func (res *Response) Cookie(name string) *http.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

func (res *Response) Flash[T any](path string) T

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

func (res *Response) JSON[T any]() T

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

func (res *Response) LoadDeferredGroups(groups ...string) *Response

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

func (res *Response) LoadDeferredProps() *Response

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

func (res *Response) Prop[T any](path string) T

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

func (res *Response) Reload() *Response

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

func (res *Response) ReloadExcept(props ...string) *Response

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

func (res *Response) ReloadOnly(props ...string) *Response

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL