What Header Shuld I Use for Put Request File Upload
HTTP Tests
- Introduction
- Making Requests
- Customizing Request Headers
- Cookies
- Session / Hallmark
- Debugging Responses
- Exception Handling
- Testing JSON APIs
- Fluent JSON Testing
- Testing File Uploads
- Testing Views
- Rendering Blade & Components
- Available Assertions
- Response Assertions
- Hallmark Assertions
Introduction
Laravel provides a very fluent API for making HTTP requests to your application and examining the responses. For case, have a look at the feature exam defined below:
<?php
namespace Tests\Feature;
apply Illuminate\Foundation\Testing\ RefreshDatabase ;
use Illuminate\Foundation\Testing\ WithoutMiddleware ;
use Tests\ TestCase ;
class ExampleTest extends TestCase
{
/**
* A bones test example.
*
* @return void
*/
public office test_a_basic_request ()
{
$response = $this -> get ( ' / ' );
$response -> assertStatus ( 200 );
}
}
The get method makes a Become asking into the application, while the assertStatus method asserts that the returned response should have the given HTTP status code. In add-on to this simple assertion, Laravel likewise contains a variety of assertions for inspecting the response headers, content, JSON structure, and more.
Making Requests
To make a asking to your application, you may invoke the get, post, put, patch, or delete methods inside your test. These methods do not actually issue a "real" HTTP request to your application. Instead, the entire network request is simulated internally.
Instead of returning an Illuminate\Http\Response instance, test request methods return an instance of Illuminate\Testing\TestResponse, which provides a variety of helpful assertions that permit you lot to inspect your application'due south responses:
<?php
namespace Tests\Characteristic;
use Illuminate\Foundation\Testing\ RefreshDatabase ;
use Illuminate\Foundation\Testing\ WithoutMiddleware ;
employ Tests\ TestCase ;
class ExampleTest extends TestCase
{
/**
* A bones test case.
*
* @render void
*/
public function test_a_basic_request ()
{
$response = $this -> get ( ' / ' );
$response -> assertStatus ( 200 );
}
}
In full general, each of your tests should only make one request to your application. Unexpected beliefs may occur if multiple requests are executed within a single test method.
{tip} For convenience, the CSRF middleware is automatically disabled when running tests.
Customizing Request Headers
Y'all may use the withHeaders method to customize the request's headers before it is sent to the application. This method allows yous to add together whatsoever custom headers you would similar to the request:
<?php
namespace Tests\Feature;
employ Tests\ TestCase ;
course ExampleTest extends TestCase
{
/**
* A basic functional examination example.
*
* @return void
*/
public function test_interacting_with_headers ()
{
$response = $this -> withHeaders ([
' X-Header ' => ' Value ' ,
]) -> post ( ' /user ' , [ ' name ' => ' Sally ' ]);
$response -> assertStatus ( 201 );
}
}
Cookies
Y'all may use the withCookie or withCookies methods to set cookie values before making a asking. The withCookie method accepts a cookie name and value every bit its 2 arguments, while the withCookies method accepts an array of name / value pairs:
<?php
namespace Tests\Characteristic;
use Tests\ TestCase ;
grade ExampleTest extends TestCase
{
public function test_interacting_with_cookies ()
{
$response = $this -> withCookie ( ' color ' , ' blue ' ) -> go ( ' / ' );
$response = $this -> withCookies ([
' color ' => ' blue ' ,
' name ' => ' Taylor ' ,
]) -> go ( ' / ' );
}
}
Session / Authentication
Laravel provides several helpers for interacting with the session during HTTP testing. Start, you may set the session information to a given array using the withSession method. This is useful for loading the session with information before issuing a asking to your application:
<?php
namespace Tests\Feature;
utilise Tests\ TestCase ;
form ExampleTest extends TestCase
{
public part test_interacting_with_the_session ()
{
$response = $this -> withSession ([ ' banned ' => imitation ]) -> go ( ' / ' );
}
}
Laravel's session is typically used to maintain state for the currently authenticated user. Therefore, the actingAs helper method provides a simple way to authenticate a given user as the current user. For example, we may use a model manufactory to generate and authenticate a user:
<?php
namespace Tests\Feature;
use App\Models\ User ;
use Tests\ TestCase ;
course ExampleTest extends TestCase
{
public role test_an_action_that_requires_authentication ()
{
$user = User :: factory () -> create ();
$response = $this -> actingAs ( $user )
-> withSession ([ ' banned ' => false ])
-> get ( ' / ' );
}
}
You may besides specify which guard should be used to authenticate the given user by passing the guard proper noun equally the second argument to the actingAs method:
$this -> actingAs ( $user , ' web ' )
Debugging Responses
After making a test request to your application, the dump, dumpHeaders, and dumpSession methods may be used to examine and debug the response contents:
<?php
namespace Tests\Feature;
use Tests\ TestCase ;
grade ExampleTest extends TestCase
{
/**
* A basic test case.
*
* @return void
*/
public function test_basic_test ()
{
$response = $this -> get ( ' / ' );
$response -> dumpHeaders ();
$response -> dumpSession ();
$response -> dump ();
}
}
Alternatively, yous may apply the dd, ddHeaders, and ddSession methods to dump information about the response and then stop execution:
<?php
namespace Tests\Characteristic;
use Tests\ TestCase ;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function test_basic_test ()
{
$response = $this -> get ( ' / ' );
$response -> ddHeaders ();
$response -> ddSession ();
$response -> dd ();
}
}
Exception Treatment
Sometimes you may want to test that your application is throwing a specific exception. To ensure that the exception does not get defenseless by Laravel's exception handler and returned as an HTTP response, you may invoke the withoutExceptionHandling method before making your request:
$response = $this -> withoutExceptionHandling () -> get ( ' / ' );
In add-on, if yous would like to ensure that your application is non utilizing features that take been deprecated by the PHP language or the libraries your application is using, you may invoke the withoutDeprecationHandling method before making your request. When deprecation treatment is disabled, deprecation warnings will be converted to exceptions, thus causing your test to fail:
$response = $this -> withoutDeprecationHandling () -> get ( ' / ' );
Testing JSON APIs
Laravel also provides several helpers for testing JSON APIs and their responses. For case, the json, getJson, postJson, putJson, patchJson, deleteJson, and optionsJson methods may exist used to issue JSON requests with various HTTP verbs. You may also easily pass data and headers to these methods. To get started, let's write a test to brand a Postal service request to /api/user and affirm that the expected JSON information was returned:
<?php
namespace Tests\Feature;
apply Tests\ TestCase ;
course ExampleTest extends TestCase
{
/**
* A bones functional examination example.
*
* @return void
*/
public function test_making_an_api_request ()
{
$response = $this -> postJson ( ' /api/user ' , [ ' name ' => ' Emerge ' ]);
$response
-> assertStatus ( 201 )
-> assertJson ([
' created ' => truthful ,
]);
}
}
In addition, JSON response data may be accessed as array variables on the response, making it user-friendly for you to audit the individual values returned within a JSON response:
$this -> assertTrue ( $response [ ' created ' ]);
{tip} The
assertJsonmethod converts the response to an array and utilizesPHPUnit::assertArraySubsetto verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this exam will still pass as long as the given fragment is present.
Asserting Exact JSON Matches
As previously mentioned, the assertJson method may exist used to affirm that a fragment of JSON exists within the JSON response. If you would like to verify that a given assortment exactly matches the JSON returned by your application, you should use the assertExactJson method:
<?php
namespace Tests\Feature;
utilize Tests\ TestCase ;
course ExampleTest extends TestCase
{
/**
* A basic functional test example.
*
* @render void
*/
public office test_asserting_an_exact_json_match ()
{
$response = $this -> postJson ( ' /user ' , [ ' proper name ' => ' Emerge ' ]);
$response
-> assertStatus ( 201 )
-> assertExactJson ([
' created ' => true ,
]);
}
}
Asserting On JSON Paths
If you would similar to verify that the JSON response contains the given data at a specified path, you should use the assertJsonPath method:
<?php
namespace Tests\Feature;
use Tests\ TestCase ;
class ExampleTest extends TestCase
{
/**
* A bones functional examination instance.
*
* @return void
*/
public function test_asserting_a_json_paths_value ()
{
$response = $this -> postJson ( ' /user ' , [ ' name ' => ' Sally ' ]);
$response
-> assertStatus ( 201 )
-> assertJsonPath ( ' squad.owner.name ' , ' Darian ' );
}
}
The assertJsonPath method also accepts a closure, which may be used to dynamically make up one's mind if the assertion should pass:
$response -> assertJsonPath ( ' team.owner.proper noun ' , fn ( $name ) => strlen ($ name ) >= 3 );
Fluent JSON Testing
Laravel also offers a cute way to fluently test your application'south JSON responses. To get started, pass a closure to the assertJson method. This closure will be invoked with an example of Illuminate\Testing\Fluent\AssertableJson which can be used to make assertions against the JSON that was returned by your application. The where method may be used to brand assertions against a detail attribute of the JSON, while the missing method may exist used to assert that a item attribute is missing from the JSON:
use Illuminate\Testing\Fluent\ AssertableJson ;
/**
* A basic functional exam instance.
*
* @return void
*/
public function test_fluent_json ()
{
$response = $this -> getJson ( ' /users/1 ' );
$response
-> assertJson ( fn ( AssertableJson $json ) =>
$json -> where ( ' id ' , ane )
-> where ( ' name ' , ' Victoria Faith ' )
-> missing ( ' password ' )
-> etc ()
);
}
Understanding The etc Method
In the example above, you lot may have noticed we invoked the etc method at the cease of our assertion chain. This method informs Laravel that there may be other attributes nowadays on the JSON object. If the etc method is non used, the test volition fail if other attributes that yous did not make assertions against exist on the JSON object.
The intention behind this behavior is to protect yous from unintentionally exposing sensitive data in your JSON responses by forcing you to either explicitly brand an assertion against the aspect or explicitly allow additional attributes via the etc method.
Asserting Aspect Presence / Absence
To affirm that an attribute is present or absent, you may apply the has and missing methods:
$response -> assertJson ( fn ( AssertableJson $json ) =>
$json -> has ( ' data ' )
-> missing ( ' bulletin ' )
);
In addition, the hasAll and missingAll methods allow asserting the presence or absence of multiple attributes simultaneously:
$response -> assertJson ( fn ( AssertableJson $json ) =>
$json -> hasAll ( ' status ' , ' data ' )
-> missingAll ( ' bulletin ' , ' lawmaking ' )
);
You may use the hasAny method to decide if at least one of a given listing of attributes is present:
$response -> assertJson ( fn ( AssertableJson $json ) =>
$json -> has ( ' status ' )
-> hasAny ( ' information ' , ' message ' , ' lawmaking ' )
);
Asserting Confronting JSON Collections
Often, your route will return a JSON response that contains multiple items, such every bit multiple users:
Route :: get ( ' /users ' , part () {
return User :: all ();
});
In these situations, we may use the fluent JSON object'due south has method to make assertions against the users included in the response. For instance, allow's assert that the JSON response contains three users. Next, we'll make some assertions about the commencement user in the collection using the first method. The first method accepts a closure which receives another assertable JSON string that nosotros tin can use to make assertions nearly the start object in the JSON collection:
$response
-> assertJson ( fn ( AssertableJson $json ) =>
$json -> has ( iii )
-> first ( fn ( $json ) =>
$json -> where ( ' id ' , one )
-> where ( ' proper name ' , ' Victoria Faith ' )
-> missing ( ' password ' )
-> etc ()
)
);
Scoping JSON Collection Assertions
Sometimes, your application'due south routes will return JSON collections that are assigned named keys:
Road :: get ( ' /users ' , function () {
return [
' meta ' => [ ... ],
' users ' => User :: all (),
];
})
When testing these routes, y'all may use the has method to assert confronting the number of items in the collection. In addition, you may use the has method to scope a chain of assertions:
$response
-> assertJson ( fn ( AssertableJson $json ) =>
$json -> has ( ' meta ' )
-> has ( ' users ' , 3 )
-> has ( ' users.0 ' , fn ( $json ) =>
$json -> where ( ' id ' , ane )
-> where ( ' name ' , ' Victoria Religion ' )
-> missing ( ' password ' )
-> etc ()
)
);
However, instead of making 2 separate calls to the has method to assert against the users collection, you may make a single phone call which provides a closure as its 3rd parameter. When doing and then, the closure will automatically exist invoked and scoped to the first item in the collection:
$response
-> assertJson ( fn ( AssertableJson $json ) =>
$json -> has ( ' meta ' )
-> has ( ' users ' , 3 , fn ( $json ) =>
$json -> where ( ' id ' , 1 )
-> where ( ' name ' , ' Victoria Organized religion ' )
-> missing ( ' countersign ' )
-> etc ()
)
);
Asserting JSON Types
You may simply desire to assert that the properties in the JSON response are of a certain blazon. The Illuminate\Testing\Fluent\AssertableJson grade provides the whereType and whereAllType methods for doing just that:
$response -> assertJson ( fn ( AssertableJson $json ) =>
$json -> whereType ( ' id ' , ' integer ' )
-> whereAllType ([
' users.0.name ' => ' string ' ,
' meta ' => ' assortment '
])
);
Y'all may specify multiple types using the | character, or passing an array of types as the second parameter to the whereType method. The assertion will be successful if the response value is any of the listed types:
$response -> assertJson ( fn ( AssertableJson $json ) =>
$json -> whereType ( ' name ' , ' cord|null ' )
-> whereType ( ' id ' , [ ' string ' , ' integer ' ])
);
The whereType and whereAllType methods recognize the following types: string, integer, double, boolean, array, and aught.
Testing File Uploads
The Illuminate\Http\UploadedFile class provides a fake method which may exist used to generate dummy files or images for testing. This, combined with the Storage facade'due south fake method, greatly simplifies the testing of file uploads. For example, you may combine these ii features to easily test an avatar upload grade:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\ RefreshDatabase ;
use Illuminate\Foundation\Testing\ WithoutMiddleware ;
use Illuminate\Http\ UploadedFile ;
utilize Illuminate\Support\Facades\ Storage ;
use Tests\ TestCase ;
class ExampleTest extends TestCase
{
public office test_avatars_can_be_uploaded ()
{
Storage :: fake ( ' avatars ' );
$file = UploadedFile :: imitation () -> epitome ( ' avatar.jpg ' );
$response = $this -> post ( ' /avatar ' , [
' avatar ' => $file ,
]);
Storage :: disk ( ' avatars ' ) -> assertExists ( $file -> hashName ());
}
}
If you would like to assert that a given file does not be, you may use the assertMissing method provided past the Storage facade:
Storage :: simulated ( ' avatars ' );
// ...
Storage :: disk ( ' avatars ' ) -> assertMissing ( ' missing.jpg ' );
Fake File Customization
When creating files using the fake method provided by the UploadedFile form, yous may specify the width, pinnacle, and size of the image (in kilobytes) in society to improve test your application's validation rules:
UploadedFile :: faux () -> image ( ' avatar.jpg ' , $width , $height ) -> size ( 100 );
In addition to creating images, you may create files of whatever other type using the create method:
UploadedFile :: faux () -> create ( ' document.pdf ' , $sizeInKilobytes );
If needed, y'all may pass a $mimeType argument to the method to explicitly define the MIME type that should exist returned by the file:
UploadedFile :: faux () -> create (
' document.pdf ' , $sizeInKilobytes , ' application/pdf '
);
Testing Views
Laravel also allows you to render a view without making a simulated HTTP request to the awarding. To reach this, yous may call the view method within your test. The view method accepts the view proper name and an optional array of data. The method returns an instance of Illuminate\Testing\TestView, which offers several methods to conveniently make assertions nearly the view's contents:
<?php
namespace Tests\Feature;
apply Tests\ TestCase ;
class ExampleTest extends TestCase
{
public office test_a_welcome_view_can_be_rendered ()
{
$view = $this -> view ( ' welcome ' , [ ' name ' => ' Taylor ' ]);
$view -> assertSee ( ' Taylor ' );
}
}
The TestView class provides the following assertion methods: assertSee, assertSeeInOrder, assertSeeText, assertSeeTextInOrder, assertDontSee, and assertDontSeeText.
If needed, you may get the raw, rendered view contents past casting the TestView instance to a string:
$contents = ( string ) $this -> view ( ' welcome ' );
Sharing Errors
Some views may depend on errors shared in the global fault bag provided by Laravel. To hydrate the mistake bag with fault messages, yous may use the withViewErrors method:
$view = $this -> withViewErrors ([
' proper name ' => [ ' Delight provide a valid name. ' ]
]) -> view ( ' class ' );
$view -> assertSee ( ' Please provide a valid name. ' );
Rendering Bract & Components
If necessary, you may use the blade method to evaluate and render a raw Blade cord. Like the view method, the blade method returns an instance of Illuminate\Testing\TestView:
$view = $this -> blade (
' <10-component :name="$name" /> ' ,
[ ' name ' => ' Taylor ' ]
);
$view -> assertSee ( ' Taylor ' );
You may use the component method to evaluate and render a Bract component. Similar the view method, the component method returns an instance of Illuminate\Testing\TestView:
$view = $this -> component ( Profile :: grade , [ ' proper name ' => ' Taylor ' ]);
$view -> assertSee ( ' Taylor ' );
Available Assertions
Response Assertions
Laravel'southward Illuminate\Testing\TestResponse form provides a variety of custom exclamation methods that you may utilize when testing your application. These assertions may be accessed on the response that is returned by the json, get, post, put, and delete test methods:
assertCookie
Assert that the response contains the given cookie:
$response -> assertCookie ( $cookieName , $value = nix );
assertCookieExpired
Assert that the response contains the given cookie and it is expired:
$response -> assertCookieExpired ( $cookieName );
assertCookieNotExpired
Affirm that the response contains the given cookie and it is not expired:
$response -> assertCookieNotExpired ( $cookieName );
assertCookieMissing
Affirm that the response does non contains the given cookie:
$response -> assertCookieMissing ( $cookieName );
assertCreated
Assert that the response has a 201 HTTP status code:
$response -> assertCreated ();
assertDontSee
Assert that the given string is not independent inside the response returned by the awarding. This assertion will automatically escape the given string unless you lot pass a second statement of false:
$response -> assertDontSee ( $value , $escaped = true );
assertDontSeeText
Assert that the given cord is not contained within the response text. This exclamation volition automatically escape the given string unless you pass a second argument of fake. This method will pass the response content to the strip_tags PHP role before making the assertion:
$response -> assertDontSeeText ( $value , $escaped = truthful );
assertDownload
Assert that the response is a "download". Typically, this means the invoked route that returned the response returned a Response::download response, BinaryFileResponse, or Storage::download response:
$response -> assertDownload ();
If you wish, yous may assert that the downloadable file was assigned a given file name:
$response -> assertDownload ( ' image.jpg ' );
assertExactJson
Assert that the response contains an exact match of the given JSON data:
$response -> assertExactJson ( assortment $information );
assertForbidden
Assert that the response has a forbidden (403) HTTP condition code:
$response -> assertForbidden ();
assertHeader
Affirm that the given header and value is present on the response:
$response -> assertHeader ( $headerName , $value = nil );
assertHeaderMissing
Assert that the given header is not present on the response:
$response -> assertHeaderMissing ( $headerName );
assertJson
Assert that the response contains the given JSON data:
$response -> assertJson ( array $data , $strict = false );
The assertJson method converts the response to an assortment and utilizes PHPUnit::assertArraySubset to verify that the given array exists within the JSON response returned by the awarding. So, if in that location are other properties in the JSON response, this test will nonetheless laissez passer every bit long equally the given fragment is present.
assertJsonCount
Assert that the response JSON has an array with the expected number of items at the given primal:
$response -> assertJsonCount ( $count , $fundamental = naught );
assertJsonFragment
Assert that the response contains the given JSON data anywhere in the response:
Route :: get ( ' /users ' , function () {
render [
' users ' => [
[
' name ' => ' Taylor Otwell ' ,
],
],
];
});
$response -> assertJsonFragment ([ ' proper name ' => ' Taylor Otwell ' ]);
assertJsonMissing
Affirm that the response does non contain the given JSON data:
$response -> assertJsonMissing ( array $information );
assertJsonMissingExact
Assert that the response does not comprise the exact JSON information:
$response -> assertJsonMissingExact ( array $data );
assertJsonMissingValidationErrors
Assert that the response has no JSON validation errors for the given keys:
$response -> assertJsonMissingValidationErrors ( $keys );
{tip} The more generic assertValid method may exist used to assert that a response does not take validation errors that were returned every bit JSON and that no errors were flashed to session storage.
assertJsonPath
Assert that the response contains the given data at the specified path:
$response -> assertJsonPath ( $path , $expectedValue );
For example, if the JSON response returned past your application contains the following data:
{
" user " : {
" name " : " Steve Schoger "
}
}
You may assert that the name property of the user object matches a given value like and then:
$response -> assertJsonPath ( ' user.name ' , ' Steve Schoger ' );
assertJsonStructure
Affirm that the response has a given JSON structure:
$response -> assertJsonStructure ( array $structure );
For case, if the JSON response returned by your application contains the post-obit data:
{
" user " : {
" proper noun " : " Steve Schoger "
}
}
Y'all may assert that the JSON construction matches your expectations like then:
$response -> assertJsonStructure ([
' user ' => [
' name ' ,
]
]);
Sometimes, JSON responses returned by your application may contain arrays of objects:
{
" user " : [
{
" proper noun " : " Steve Schoger " ,
" age " : 55 ,
" location " : " Earth "
},
{
" name " : " Mary Schoger " ,
" age " : 60 ,
" location " : " Globe "
}
]
}
In this situation, you may use the * character to assert against the structure of all of the objects in the array:
$response -> assertJsonStructure ([
' user ' => [
' * ' => [
' name ' ,
' age ' ,
' location '
]
]
]);
assertJsonValidationErrors
Assert that the response has the given JSON validation errors for the given keys. This method should exist used when asserting against responses where the validation errors are returned as a JSON construction instead of being flashed to the session:
$response -> assertJsonValidationErrors ( array $data , $responseKey = ' errors ' );
{tip} The more generic assertInvalid method may be used to assert that a response has validation errors returned equally JSON or that errors were flashed to session storage.
assertJsonValidationErrorFor
Assert the response has any JSON validation errors for the given key:
$response -> assertJsonValidationErrorFor ( string $key , $responseKey = ' errors ' );
assertLocation
Assert that the response has the given URI value in the Location header:
$response -> assertLocation ( $uri );
assertNoContent
Assert that the response has the given HTTP status code and no content:
$response -> assertNoContent ( $status = 204 );
assertNotFound
Assert that the response has a non found (404) HTTP status lawmaking:
$response -> assertNotFound ();
assertOk
Assert that the response has a 200 HTTP status lawmaking:
$response -> assertOk ();
assertPlainCookie
Assert that the response contains the given unencrypted cookie:
$response -> assertPlainCookie ( $cookieName , $value = null );
assertRedirect
Assert that the response is a redirect to the given URI:
$response -> assertRedirect ( $uri );
assertRedirectContains
Assert whether the response is redirecting to a URI that contains the given cord:
$response -> assertRedirectContains ( $string );
assertRedirectToSignedRoute
Affirm that the response is a redirect to the given signed road:
$response -> assertRedirectToSignedRoute ( $name = null , $parameters = []);
assertSee
Affirm that the given cord is independent within the response. This assertion will automatically escape the given string unless you laissez passer a 2d argument of false:
$response -> assertSee ( $value , $escaped = true );
assertSeeInOrder
Assert that the given strings are independent in order within the response. This assertion will automatically escape the given strings unless y'all pass a second argument of false:
$response -> assertSeeInOrder ( array $values , $escaped = true );
assertSeeText
Assert that the given cord is contained within the response text. This assertion volition automatically escape the given string unless you pass a 2nd argument of false. The response content volition be passed to the strip_tags PHP office before the assertion is made:
$response -> assertSeeText ( $value , $escaped = true );
assertSeeTextInOrder
Assert that the given strings are contained in order within the response text. This exclamation will automatically escape the given strings unless y'all pass a second statement of false. The response content volition be passed to the strip_tags PHP function before the assertion is fabricated:
$response -> assertSeeTextInOrder ( assortment $values , $escaped = true );
assertSessionHas
Affirm that the session contains the given slice of data:
$response -> assertSessionHas ( $key , $value = null );
If needed, a closure can be provided equally the second argument to the assertSessionHas method. The exclamation will pass if the closure returns true:
$response -> assertSessionHas ( $key , function ( $value ) {
return $value ->name === ' Taylor Otwell ' ;
});
assertSessionHasInput
Assert that the session has a given value in the flashed input array:
$response -> assertSessionHasInput ( $key , $value = nil );
If needed, a closure can exist provided as the second statement to the assertSessionHasInput method. The assertion will pass if the closure returns truthful:
$response -> assertSessionHasInput ( $central , office ( $value ) {
render Crypt :: decryptString ( $value ) === ' secret ' ;
});
assertSessionHasAll
Assert that the session contains a given array of key / value pairs:
$response -> assertSessionHasAll ( assortment $data );
For example, if your application's session contains name and status keys, you may assert that both be and have the specified values like and then:
$response -> assertSessionHasAll ([
' name ' => ' Taylor Otwell ' ,
' status ' => ' agile ' ,
]);
assertSessionHasErrors
Assert that the session contains an mistake for the given $keys. If $keys is an associative assortment, affirm that the session contains a specific error message (value) for each field (key). This method should be used when testing routes that flash validation errors to the session instead of returning them as a JSON construction:
$response -> assertSessionHasErrors (
assortment $keys , $format = null , $errorBag = ' default '
);
For case, to assert that the name and email fields have validation error letters that were flashed to the session, you may invoke the assertSessionHasErrors method similar then:
$response -> assertSessionHasErrors ([ ' proper noun ' , ' email ' ]);
Or, yous may assert that a given field has a item validation mistake message:
$response -> assertSessionHasErrors ([
' name ' => ' The given name was invalid. '
]);
{tip} The more generic assertInvalid method may be used to assert that a response has validation errors returned as JSON or that errors were flashed to session storage.
assertSessionHasErrorsIn
Affirm that the session contains an error for the given $keys within a specific fault bag. If $keys is an associative array, assert that the session contains a specific error bulletin (value) for each field (key), inside the error bag:
$response -> assertSessionHasErrorsIn ( $errorBag , $keys = [], $format = cipher );
assertSessionHasNoErrors
Assert that the session has no validation errors:
$response -> assertSessionHasNoErrors ();
assertSessionDoesntHaveErrors
Affirm that the session has no validation errors for the given keys:
$response -> assertSessionDoesntHaveErrors ( $keys = [], $format = nix , $errorBag = ' default ' );
{tip} The more generic assertValid method may exist used to assert that a response does non have validation errors that were returned every bit JSON and that no errors were flashed to session storage.
assertSessionMissing
Assert that the session does not contain the given central:
$response -> assertSessionMissing ( $key );
assertStatus
Assert that the response has a given HTTP status code:
$response -> assertStatus ( $code );
assertSuccessful
Assert that the response has a successful (>= 200 and < 300) HTTP condition code:
$response -> assertSuccessful ();
assertUnauthorized
Assert that the response has an unauthorized (401) HTTP status code:
$response -> assertUnauthorized ();
assertUnprocessable
Affirm that the response has an unprocessable entity (422) HTTP status code:
$response -> assertUnprocessable ();
assertValid
Assert that the response has no validation errors for the given keys. This method may be used for asserting against responses where the validation errors are returned every bit a JSON structure or where the validation errors have been flashed to the session:
// Assert that no validation errors are nowadays...
$response -> assertValid ();
// Affirm that the given keys do not have validation errors...
$response -> assertValid ([ ' name ' , ' electronic mail ' ]);
assertInvalid
Assert that the response has validation errors for the given keys. This method may be used for asserting confronting responses where the validation errors are returned equally a JSON construction or where the validation errors take been flashed to the session:
$response -> assertInvalid ([ ' name ' , ' email ' ]);
You may also assert that a given fundamental has a particular validation error bulletin. When doing so, you may provide the entire bulletin or only a minor portion of the message:
$response -> assertInvalid ([
' name ' => ' The name field is required. ' ,
' electronic mail ' => ' valid email address ' ,
]);
assertViewHas
Assert that the response view contains given a piece of data:
$response -> assertViewHas ( $fundamental , $value = null );
Passing a closure as the second argument to the assertViewHas method will allow you to inspect and make assertions against a particular piece of view data:
$response -> assertViewHas ( ' user ' , function ( User $user ) {
render $user ->name === ' Taylor ' ;
});
In improver, view data may be accessed as assortment variables on the response, allowing you lot to conveniently inspect information technology:
$this -> assertEquals ( ' Taylor ' , $response [ ' name ' ]);
assertViewHasAll
Affirm that the response view has a given listing of data:
$response -> assertViewHasAll ( array $data );
This method may be used to assert that the view simply contains data matching the given keys:
$response -> assertViewHasAll ([
' proper name ' ,
' email ' ,
]);
Or, you may affirm that the view data is present and has specific values:
$response -> assertViewHasAll ([
' name ' => ' Taylor Otwell ' ,
' email ' => ' [email protected], ' ,
]);
assertViewIs
Affirm that the given view was returned by the route:
$response -> assertViewIs ( $value );
assertViewMissing
Assert that the given information central was not fabricated bachelor to the view returned in the awarding'southward response:
$response -> assertViewMissing ( $key );
Authentication Assertions
Laravel besides provides a variety of hallmark related assertions that you may utilize within your application's feature tests. Note that these methods are invoked on the exam class itself and not the Illuminate\Testing\TestResponse instance returned by methods such as get and mail.
assertAuthenticated
Affirm that a user is authenticated:
$this -> assertAuthenticated ( $guard = cypher );
assertGuest
Assert that a user is non authenticated:
$this -> assertGuest ( $guard = null );
assertAuthenticatedAs
Assert that a specific user is authenticated:
$this -> assertAuthenticatedAs ( $user , $guard = null );
Source: https://laravel.com/docs/9.x/http-tests
0 Response to "What Header Shuld I Use for Put Request File Upload"
Enregistrer un commentaire