LaraflareDocsFrameworkPackagesReleases13.x

Docs / Testing / HTTP Tests

HTTP Tests

Introduction

laraflare provides a very fluent API for making HTTP requests to your application and examining the responses. For example, take a look at the feature test defined below:

import { test } from '../Pest';

test('the application returns a successful response', async function () {
  const response = await this.get('/');

  response.assertStatus(200);
});

The get method makes a GET request into the application, while the assertStatus method asserts that the returned response should have the given HTTP status code. In addition to this simple assertion, laraflare also contains a variety of assertions for inspecting the response headers, content, JSON structure, and more.

Making Requests

To make a request to your application, you may invoke the get, post, put, patch, or delete methods within 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 a plain response, test request methods return a promise of a TestResponse instance, which provides a variety of helpful assertions that allow you to inspect your application's responses:

import { test } from '../Pest';

test('basic request', async function () {
  const response = await this.get('/');

  response.assertStatus(200);
});

In general, each of your tests should only make one request to your application. Unexpected behavior may occur if multiple requests are executed within a single test.

Note

For convenience, the CSRF middleware is automatically disabled when running tests.

Customizing Request Headers

You may use the withHeaders method to customize the request's headers before it is sent to the application. This method allows you to add any custom headers you would like to the request:

import { test } from '../Pest';

test('interacting with headers', async function () {
  const response = await this.withHeaders({
    'X-Header': 'Value',
  }).post('/user', { name: 'Sally' });

  response.assertStatus(201);
});

Cookies

You may use the withCookie or withCookies methods to set cookie values before making a request. The withCookie method accepts a cookie name and value as its two arguments, while the withCookies method accepts an object of name / value pairs:

import { test } from '../Pest';

test('interacting with cookies', async function () {
  let response = await this.withCookie('color', 'blue').get('/');

  response = await this.withCookies({
    color: 'blue',
    name: 'Taylor',
  }).get('/');

  //
});

Session / Authentication

laraflare provides several helpers for interacting with the session during HTTP testing. First, you may set the session data to a given object using the withSession method. This is useful for loading the session with data before issuing a request to your application:

import { test } from '../Pest';

test('interacting with the session', async function () {
  const response = await this.withSession({ banned: false }).get('/');

  //
});

laraflare'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 factory to generate and authenticate a user:

import { User } from '../../app/Models/User';
import { test } from '../Pest';

test('an action that requires authentication', async function () {
  const user = await User.factory().create();

  const response = await this.actingAs(user)
    .withSession({ banned: false })
    .get('/');

  //
});

You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the actingAs method. The guard that is provided to the actingAs method will also become the default guard for the duration of the test:

this.actingAs(user, 'web');

If you would like to ensure the request is unauthenticated, you may use the actingAsGuest method:

this.actingAsGuest();

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:

import { test } from '../Pest';

test('basic test', async function () {
  const response = await this.get('/');

  response.dump();
  response.dumpHeaders();
  response.dumpSession();
});

Alternatively, you may use the dd, ddHeaders, ddBody, ddJson, and ddSession methods to dump information about the response and then stop execution:

import { test } from '../Pest';

test('basic test', async function () {
  const response = await this.get('/');

  response.dd();
  response.ddHeaders();
  response.ddBody();
  response.ddJson();
  response.ddSession();
});

Exception Handling

Sometimes you may need to test that your application is throwing a specific exception. To accomplish this, you may "fake" the exception handler via the Exceptions facade. Once the exception handler has been faked, you may utilize the assertReported and assertNotReported methods to make assertions against exceptions that were thrown during the request:

import { InvalidOrderException } from '../../app/Exceptions/InvalidOrderException';
import { test } from '../Pest';

test('exception is thrown', async function () {
  Exceptions.fake();

  const response = await this.get('/order/1');

  // Assert an exception was thrown...
  Exceptions.assertReported(InvalidOrderException);

  // Assert against the exception...
  Exceptions.assertReported((e: InvalidOrderException) => {
    return e.message === 'The order was invalid.';
  });
});

The assertNotReported and assertNothingReported methods may be used to assert that a given exception was not thrown during the request or that no exceptions were thrown:

Exceptions.assertNotReported(InvalidOrderException);

Exceptions.assertNothingReported();

You may totally disable exception handling for a given request by invoking the withoutExceptionHandling method before making your request:

const response = await this.withoutExceptionHandling().get('/');

In addition, if you would like to ensure that your application is not utilizing features that have been deprecated by the libraries your application is using, you may invoke the withoutDeprecationHandling method before making your request. When deprecation handling is disabled, deprecation warnings will be converted to exceptions, thus causing your test to fail:

const response = await this.withoutDeprecationHandling().get('/');

The assertThrows method may be used to assert that code within a given closure throws an exception of the specified type:

await this.assertThrows(
  () => new ProcessOrder().execute(),
  OrderInvalid,
);

If you would like to inspect and make assertions against the exception that is thrown, you may provide a closure as the second argument to the assertThrows method:

await this.assertThrows(
  () => new ProcessOrder().execute(),
  (e: OrderInvalid) => e.orderId() === 123,
);

The assertDoesntThrow method may be used to assert that the code within a given closure does not throw any exceptions:

await this.assertDoesntThrow(() => new ProcessOrder().execute());

Testing JSON APIs

laraflare also provides several helpers for testing JSON APIs and their responses. For example, the json, getJson, postJson, putJson, patchJson, deleteJson, and optionsJson methods may be 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 make a POST request to /api/user and assert that the expected JSON data was returned:

import { test } from '../Pest';

test('making an api request', async function () {
  const response = await this.postJson('/api/user', { name: 'Sally' });

  response
    .assertStatus(201)
    .assertJson({
      created: true,
    });
});

In addition, the response's JSON data may be read with the json method, making it convenient for you to inspect the individual values returned within a JSON response:

expect(response.json('created')).toBeTrue();

Note

The assertJson method converts the response to an object to verify that the given object exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.

Asserting Exact JSON Matches

As previously mentioned, the assertJson method may be used to assert that a fragment of JSON exists within the JSON response. If you would like to verify that a given object exactly matches the JSON returned by your application, you should use the assertExactJson method:

import { test } from '../Pest';

test('asserting an exact json match', async function () {
  const response = await this.postJson('/user', { name: 'Sally' });

  response
    .assertStatus(201)
    .assertExactJson({
      created: true,
    });
});

Asserting on JSON Paths

If you would like to verify that the JSON response contains the given data at a specified path, you should use the assertJsonPath method:

import { test } from '../Pest';

test('asserting a json path value', async function () {
  const response = await this.postJson('/user', { name: 'Sally' });

  response
    .assertStatus(201)
    .assertJsonPath('team.owner.name', 'Darian');
});

The assertJsonPath method also accepts a closure, which may be used to dynamically determine if the assertion should pass:

response.assertJsonPath('team.owner.name', (name: string) => name.length >= 3);

If you need to assert multiple JSON paths at once, you may use the assertJsonPaths method. The expected value for each path may also be a closure:

response.assertJsonPaths({
  'team.owner.name': 'Darian',
  'team.owner.email': (email: string) => email.endsWith('@example.com'),
  'team.members.0.name': 'Sally',
});

You may use the assertJsonMissingPaths method to assert that multiple JSON paths are missing from the response:

response.assertJsonMissingPaths([
  'team.owner.password',
  'team.members.0.api_token',
]);

Fluent JSON Testing

laraflare also offers a beautiful way to fluently test your application's JSON responses. To get started, pass a closure to the assertJson method. This closure will be invoked with an AssertableJson instance which can be used to make assertions against the JSON that was returned by your application. The where method may be used to make assertions against a particular attribute of the JSON, while the missing method may be used to assert that a particular attribute is missing from the JSON:

import { test } from '../Pest';

test('fluent json', async function () {
  const response = await this.getJson('/users/1');

  response
    .assertJson((json) =>
      json.where('id', 1)
        .where('name', 'Victoria Faith')
        .where('email', (email: string) => email === 'victoria@gmail.com')
        .whereNot('status', 'pending')
        .missing('password')
        .etc()
    );
});

Understanding the etc Method

In the example above, you may have noticed we invoked the etc method at the end of our assertion chain. This method informs laraflare that there may be other attributes present on the JSON object. If the etc method is not used, the test will fail if other attributes that you did not make assertions against exist on the JSON object.

The intention behind this behavior is to protect you from unintentionally exposing sensitive information in your JSON responses by forcing you to either explicitly make an assertion against the attribute or explicitly allow additional attributes via the etc method.

However, you should be aware that not including the etc method in your assertion chain does not ensure that additional attributes are not being added to arrays that are nested within your JSON object. The etc method only ensures that no additional attributes exist at the nesting level in which the etc method is invoked.

Asserting Attribute Presence / Absence

To assert that an attribute is present or absent, you may use the has and missing methods:

response.assertJson((json) =>
  json.has('data')
    .missing('message')
);

In addition, the hasAll and missingAll methods allow asserting the presence or absence of multiple attributes simultaneously:

response.assertJson((json) =>
  json.hasAll(['status', 'data'])
    .missingAll(['message', 'code'])
);

You may use the hasAny method to determine if at least one of a given list of attributes is present:

response.assertJson((json) =>
  json.has('status')
    .hasAny('data', 'message', 'code')
);

Asserting Against JSON Collections

Often, your route will return a JSON response that contains multiple items, such as multiple users:

Route.get('/users', async () => {
  return User.all();
});

In these situations, we may use the fluent JSON object's has method to make assertions against the users included in the response. For example, let's assert that the JSON response contains three users. Next, we'll make some assertions about the first user in the collection using the first method. The first method accepts a closure which receives another assertable JSON object that we can use to make assertions about the first object in the JSON collection:

response
  .assertJson((json) =>
    json.has(3)
      .first((json) =>
        json.where('id', 1)
          .where('name', 'Victoria Faith')
          .where('email', (email: string) => email === 'victoria@gmail.com')
          .missing('password')
          .etc()
      )
  );

If you would like to make the same assertions against every item in a JSON collection, you may use the each method:

response
  .assertJson((json) =>
    json.has(3)
      .each((json) =>
        json.whereType('id', 'integer')
          .whereType('name', 'string')
          .whereType('email', 'string')
          .missing('password')
          .etc()
      )
  );

Scoping JSON Collection Assertions

Sometimes, your application's routes will return JSON collections that are assigned named keys:

Route.get('/users', async () => {
  return {
    meta: { /* ... */ },
    users: await User.all(),
  };
});

When testing these routes, you may use the has method to assert against the number of items in the collection. In addition, you may use the has method to scope a chain of assertions:

response
  .assertJson((json) =>
    json.has('meta')
      .has('users', 3)
      .has('users.0', (json) =>
        json.where('id', 1)
          .where('name', 'Victoria Faith')
          .where('email', (email: string) => email === 'victoria@gmail.com')
          .missing('password')
          .etc()
      )
  );

However, instead of making two separate calls to the has method to assert against the users collection, you may make a single call which provides a closure as its third parameter. When doing so, the closure will automatically be invoked and scoped to the first item in the collection:

response
  .assertJson((json) =>
    json.has('meta')
      .has('users', 3, (json) =>
        json.where('id', 1)
          .where('name', 'Victoria Faith')
          .where('email', (email: string) => email === 'victoria@gmail.com')
          .missing('password')
          .etc()
      )
  );

Asserting JSON Types

You may only want to assert that the properties in the JSON response are of a certain type. The AssertableJson class provides the whereType and whereAllType methods for doing just that:

response.assertJson((json) =>
  json.whereType('id', 'integer')
    .whereAllType({
      'users.0.name': 'string',
      meta: 'array',
    })
);

You 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((json) =>
  json.whereType('name', 'string|null')
    .whereType('id', ['string', 'integer'])
);

The whereType and whereAllType methods recognize the following types: string, integer, double, boolean, array, and null.

Testing File Uploads

The UploadedFile class provides a fake method which may be used to generate dummy files or images for testing. This, combined with the Storage facade's fake method, greatly simplifies the testing of file uploads. For example, you may combine these two features to easily test an avatar upload form:

import { Storage, UploadedFile } from '@laraflare/framework';
import { test } from '../Pest';

test('avatars can be uploaded', async function () {
  Storage.fake('avatars');

  const file = UploadedFile.fake().image('avatar.jpg');

  const response = await this.post('/avatar', {
    avatar: file,
  });

  await Storage.disk('avatars').assertExists(file.hashName());
});

If you would like to assert that a given file does not exist, you may use the assertMissing method provided by the Storage facade:

Storage.fake('avatars');

// ...

await Storage.disk('avatars').assertMissing('missing.jpg');

Fake File Customization

When creating files using the fake method provided by the UploadedFile class, you may specify the width, height, and size of the image (in kilobytes) in order to better test your application's validation rules:

UploadedFile.fake().image('avatar.jpg', width, height).size(100);

In addition to creating images, you may create files of any other type using the create method:

UploadedFile.fake().create('document.pdf', sizeInKilobytes);

If needed, you may pass a mimeType argument to the method to explicitly define the MIME type that should be returned by the file:

UploadedFile.fake().create(
  'document.pdf', sizeInKilobytes, 'application/pdf',
);

Note

laraflare's screens are Vue, so there are no helpers for rendering a view on its own: test a screen through the response it is returned in.

Available Assertions

Response Assertions

laraflare's TestResponse class provides a variety of custom assertion 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:

assertAccepted assertBadRequest assertClientError assertConflict assertCookie assertCookieExpired assertCookieNotExpired assertCookieMissing assertCreated assertDontSee assertDontSeeHtml assertDontSeeText assertDownload assertExactJson assertExactJsonStructure assertFailedDependency assertForbidden assertFound assertGone assertHeader assertHeaderContains assertHeaderMissing assertInternalServerError assertJson assertJsonCount assertJsonFragment assertJsonIsArray assertJsonIsObject assertJsonMissing assertJsonMissingExact assertJsonMissingValidationErrors assertJsonPath assertJsonPaths assertJsonMissingPath assertJsonMissingPaths assertJsonStructure assertJsonValidationErrors assertJsonValidationErrorFor assertLocation assertMethodNotAllowed assertMovedPermanently assertContent assertNoContent assertStreamed assertStreamedContent assertNotFound assertOk assertPaymentRequired assertPlainCookie assertRedirect assertRedirectBack assertRedirectBackWithErrors assertRedirectBackWithoutErrors assertRedirectContains assertRedirectToRoute assertRedirectToSignedRoute assertRequestTimeout assertSee assertSeeHtml assertSeeHtmlInOrder assertSeeInOrder assertSeeText assertSeeTextInOrder assertServerError assertServiceUnavailable assertSessionHas assertSessionHasInput assertSessionHasAll assertSessionHasErrors assertSessionHasErrorsIn assertSessionHasNoErrors assertSessionDoesntHaveErrors assertSessionMissing assertSessionMissingInput assertStatus assertSuccessful assertTooManyRequests assertUnauthorized assertUnprocessable assertUnsupportedMediaType assertValid assertInvalid

assertAccepted

Assert that the response has an accepted (202) HTTP status code:

response.assertAccepted();

assertBadRequest

Assert that the response has a bad request (400) HTTP status code:

response.assertBadRequest();

assertClientError

Assert that the response has a client error (>= 400, < 500) HTTP status code:

response.assertClientError();

assertConflict

Assert that the response has a conflict (409) HTTP status code:

response.assertConflict();

assertCookie

Assert that the response contains the given cookie:

response.assertCookie(cookieName, value);

assertCookieExpired

Assert that the response contains the given cookie and it is expired:

response.assertCookieExpired(cookieName);

assertCookieNotExpired

Assert that the response contains the given cookie and it is not expired:

response.assertCookieNotExpired(cookieName);

assertCookieMissing

Assert that the response does not contain 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 contained within the response returned by the application. This assertion will automatically escape the given string unless you pass a second argument of false:

response.assertDontSee(value, escape);

assertDontSeeHtml

Assert that the given HTML string is not contained within the response returned by the application. This assertion is an alias to assertDontSee with its escape argument set to false:

response.assertDontSeeHtml(value);

assertDontSeeText

Assert that the given string is not contained within the response text. This assertion will automatically escape the given string unless you pass a second argument of false. The HTML tags are stripped from the response content before the assertion is made:

response.assertDontSeeText(value, escape);

assertDownload

Assert that the response is a "download". Typically, this means the invoked route that returned the response returned a download response:

response.assertDownload();

If you wish, you 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(data);

assertExactJsonStructure

Assert that the response contains an exact match of the given JSON structure:

response.assertExactJsonStructure(data);

This method is a more strict variant of assertJsonStructure. In contrast with assertJsonStructure, this method will fail if the response contains any keys that aren't explicitly included in the expected JSON structure.

assertFailedDependency

Assert that the response has a failed dependency (424) HTTP status code:

response.assertFailedDependency();

assertForbidden

Assert that the response has a forbidden (403) HTTP status code:

response.assertForbidden();

assertFound

Assert that the response has a found (302) HTTP status code:

response.assertFound();

assertGone

Assert that the response has a gone (410) HTTP status code:

response.assertGone();

assertHeader

Assert that the given header and value is present on the response:

response.assertHeader(headerName, value);

assertHeaderContains

Assert that the given header contains a given substring value:

response.assertHeaderContains(headerName, value);

assertHeaderMissing

Assert that the given header is not present on the response:

response.assertHeaderMissing(headerName);

assertInternalServerError

Assert that the response has an "Internal Server Error" (500) HTTP status code:

response.assertInternalServerError();

assertJson

Assert that the response contains the given JSON data:

response.assertJson(data);

The assertJson method converts the response to an object to verify that the given object exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.

assertJsonCount

Assert that the response JSON has an array with the expected number of items at the given key:

response.assertJsonCount(count, key);

assertJsonFragment

Assert that the response contains the given JSON data anywhere in the response:

Route.get('/users', () => {
  return {
    users: [
      {
        name: 'Taylor Otwell',
      },
    ],
  };
});

response.assertJsonFragment({ name: 'Taylor Otwell' });

assertJsonIsArray

Assert that the response JSON is an array:

response.assertJsonIsArray();

assertJsonIsObject

Assert that the response JSON is an object:

response.assertJsonIsObject();

assertJsonMissing

Assert that the response does not contain the given JSON data:

response.assertJsonMissing(data);

assertJsonMissingExact

Assert that the response does not contain the exact JSON data:

response.assertJsonMissingExact(data);

assertJsonMissingValidationErrors

Assert that the response has no JSON validation errors for the given keys:

response.assertJsonMissingValidationErrors(keys);

Note

The more generic assertValid method may be used to assert that a response does not have validation errors that were returned as 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 following JSON response is returned by your application:

{
    "user": {
        "name": "Steve Schoger"
    }
}

You may assert that the name property of the user object matches a given value like so:

response.assertJsonPath('user.name', 'Steve Schoger');

assertJsonPaths

Assert that the response contains the given data at the specified paths:

response.assertJsonPaths(paths);

For example, you may assert multiple values within the response at once:

response.assertJsonPaths({
  'user.name': 'Steve Schoger',
  'user.email': (email: string) => email.endsWith('@example.com'),
});

assertJsonMissingPath

Assert that the response does not contain the given path:

response.assertJsonMissingPath(path);

For example, if the following JSON response is returned by your application:

{
    "user": {
        "name": "Steve Schoger"
    }
}

You may assert that it does not contain the email property of the user object:

response.assertJsonMissingPath('user.email');

assertJsonMissingPaths

Assert that the response does not contain the given paths:

response.assertJsonMissingPaths(paths);

For example, you may assert that multiple paths are missing from the response:

response.assertJsonMissingPaths([
  'user.email',
  'user.password',
]);

assertJsonStructure

Assert that the response has a given JSON structure:

response.assertJsonStructure(structure);

For example, if the JSON response returned by your application contains the following data:

{
    "user": {
        "name": "Steve Schoger"
    }
}

You may assert that the JSON structure matches your expectations like so:

response.assertJsonStructure({
  user: [
    'name',
  ],
});

Sometimes, JSON responses returned by your application may contain arrays of objects:

{
    "user": [
        {
            "name": "Steve Schoger",
            "age": 55,
            "location": "Earth"
        },
        {
            "name": "Mary Schoger",
            "age": 60,
            "location": "Earth"
        }
    ]
}

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 be used when asserting against responses where the validation errors are returned as a JSON structure instead of being flashed to the session:

response.assertJsonValidationErrors(data, responseKey);

Note

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.

assertJsonValidationErrorFor

Assert the response has any JSON validation errors for the given key:

response.assertJsonValidationErrorFor(key, responseKey);

assertMethodNotAllowed

Assert that the response has a method not allowed (405) HTTP status code:

response.assertMethodNotAllowed();

assertMovedPermanently

Assert that the response has a moved permanently (301) HTTP status code:

response.assertMovedPermanently();

assertLocation

Assert that the response has the given URI value in the Location header:

response.assertLocation(uri);

assertContent

Assert that the given string matches the response content:

response.assertContent(value);

assertNoContent

Assert that the response has the given HTTP status code and no content:

response.assertNoContent(status);

assertStreamed

Assert that the response was a streamed response:

response.assertStreamed();

assertStreamedContent

Assert that the given string matches the streamed response content:

await response.assertStreamedContent(value);

assertNotFound

Assert that the response has a not found (404) HTTP status code:

response.assertNotFound();

assertOk

Assert that the response has a 200 HTTP status code:

response.assertOk();

assertPaymentRequired

Assert that the response has a payment required (402) HTTP status code:

response.assertPaymentRequired();

assertPlainCookie

Assert that the response contains the given unencrypted cookie:

response.assertPlainCookie(cookieName, value);

assertRedirect

Assert that the response is a redirect to the given URI:

response.assertRedirect(uri);

assertRedirectBack

Assert whether the response is redirecting back to the previous page:

response.assertRedirectBack();

assertRedirectBackWithErrors

Assert whether the response is redirecting back to the previous page and the session has the given errors:

response.assertRedirectBackWithErrors(keys, format, errorBag);

assertRedirectBackWithoutErrors

Assert whether the response is redirecting back to the previous page and the session does not contain any error messages:

response.assertRedirectBackWithoutErrors();

assertRedirectContains

Assert whether the response is redirecting to a URI that contains the given string:

response.assertRedirectContains(string);

assertRedirectToRoute

Assert that the response is a redirect to the given named route:

response.assertRedirectToRoute(name, parameters);

assertRedirectToSignedRoute

Assert that the response is a redirect to the given signed route:

response.assertRedirectToSignedRoute(name, parameters);

assertRequestTimeout

Assert that the response has a request timeout (408) HTTP status code:

response.assertRequestTimeout();

assertSee

Assert that the given string is contained within the response. This assertion will automatically escape the given string unless you pass a second argument of false:

response.assertSee(value, escape);

assertSeeHtml

Assert that the given HTML string or array of HTML strings are contained within the response. This assertion is an alias to assertSee with its escape argument set to false:

response.assertSeeHtml(value);

assertSeeHtmlInOrder

Assert that the given HTML strings are contained in order within the response. This assertion is an alias to assertSeeInOrder with its escape argument set to false:

response.assertSeeHtmlInOrder(values);

assertSeeInOrder

Assert that the given strings are contained in order within the response. This assertion will automatically escape the given strings unless you pass a second argument of false:

response.assertSeeInOrder(values, escape);

assertSeeText

Assert that the given string is contained within the response text. This assertion will automatically escape the given string unless you pass a second argument of false. The HTML tags are stripped from the response content before the assertion is made:

response.assertSeeText(value, escape);

assertSeeTextInOrder

Assert that the given strings are contained in order within the response text. This assertion will automatically escape the given strings unless you pass a second argument of false. The HTML tags are stripped from the response content before the assertion is made:

response.assertSeeTextInOrder(values, escape);

assertServerError

Assert that the response has a server error (>= 500 , < 600) HTTP status code:

response.assertServerError();

assertServiceUnavailable

Assert that the response has a "Service Unavailable" (503) HTTP status code:

response.assertServiceUnavailable();

assertSessionHas

Assert that the session contains the given piece of data:

response.assertSessionHas(key, value);

If needed, a closure can be provided as the second argument to the assertSessionHas method. The assertion will pass if the closure returns true:

response.assertSessionHas(key, (value: User) => {
  return value.name === 'Taylor Otwell';
});

assertSessionHasInput

Assert that the session has a given value in the flashed input array:

response.assertSessionHasInput(key, value);

If needed, a closure can be provided as the second argument to the assertSessionHasInput method. The assertion will pass if the closure returns true:

response.assertSessionHasInput(key, (value: string) => {
  return value === 'secret';
});

assertSessionHasAll

Assert that the session contains a given object of key / value pairs:

response.assertSessionHasAll(data);

For example, if your application's session contains name and status keys, you may assert that both exist and have the specified values like so:

response.assertSessionHasAll({
  name: 'Taylor Otwell',
  status: 'active',
});

assertSessionHasErrors

Assert that the session contains an error for the given keys. If keys is an object, assert 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 structure:

response.assertSessionHasErrors(keys, format, errorBag);

For example, to assert that the name and email fields have validation error messages that were flashed to the session, you may invoke the assertSessionHasErrors method like so:

response.assertSessionHasErrors(['name', 'email']);

Or, you may assert that a given field has a particular validation error message:

response.assertSessionHasErrors({
  name: 'The given name was invalid.',
});

Note

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

Assert that the session contains an error for the given keys within a specific error bag. If keys is an object, assert that the session contains a specific error message (value) for each field (key), within the error bag:

response.assertSessionHasErrorsIn(errorBag, keys, format);

assertSessionHasNoErrors

Assert that the session has no validation errors:

response.assertSessionHasNoErrors();

assertSessionDoesntHaveErrors

Assert that the session has no validation errors for the given keys:

response.assertSessionDoesntHaveErrors(keys, format, errorBag);

Note

The more generic assertValid method may be used to assert that a response does not have validation errors that were returned as JSON and that no errors were flashed to session storage.

assertSessionMissing

Assert that the session does not contain the given key:

response.assertSessionMissing(key);

assertSessionMissingInput

Assert that the session is missing the given input key in the flashed input array:

response.assertSessionMissingInput(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 status code:

response.assertSuccessful();

assertTooManyRequests

Assert that the response has a too many requests (429) HTTP status code:

response.assertTooManyRequests();

assertUnauthorized

Assert that the response has an unauthorized (401) HTTP status code:

response.assertUnauthorized();

assertUnprocessable

Assert that the response has an unprocessable entity (422) HTTP status code:

response.assertUnprocessable();

assertUnsupportedMediaType

Assert that the response has an unsupported media type (415) HTTP status code:

response.assertUnsupportedMediaType();

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 as a JSON structure or where the validation errors have been flashed to the session:

// Assert that no validation errors are present...
response.assertValid();

// Assert that the given keys do not have validation errors...
response.assertValid(['name', 'email']);

assertInvalid

Assert that the response has validation errors for the given keys. This method may be used for asserting against responses where the validation errors are returned as a JSON structure or where the validation errors have been flashed to the session:

response.assertInvalid(['name', 'email']);

You may also assert that a given key has a particular validation error message. When doing so, you may provide the entire message or only a small portion of the message:

response.assertInvalid({
  name: 'The name field is required.',
  email: 'valid email address',
});

If you would like to assert that the given fields are the only fields with validation errors, you may use the assertOnlyInvalid method:

response.assertOnlyInvalid(['name', 'email']);

Authentication Assertions

laraflare also provides a variety of authentication related assertions that you may utilize within your application's feature tests. Note that these methods are invoked on the test case itself and not the TestResponse instance returned by methods such as get and post.

assertAuthenticated

Assert that a user is authenticated:

await this.assertAuthenticated(guard);

assertGuest

Assert that a user is not authenticated:

await this.assertGuest(guard);

assertAuthenticatedAs

Assert that a specific user is authenticated:

await this.assertAuthenticatedAs(user, guard);

Validation Assertions

laraflare provides two primary validation related assertions that you may use to ensure the data provided in your request was either valid or invalid.

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 as a JSON structure or where the validation errors have been flashed to the session:

// Assert that no validation errors are present...
response.assertValid();

// Assert that the given keys do not have validation errors...
response.assertValid(['name', 'email']);

assertInvalid

Assert that the response has validation errors for the given keys. This method may be used for asserting against responses where the validation errors are returned as a JSON structure or where the validation errors have been flashed to the session:

response.assertInvalid(['name', 'email']);

You may also assert that a given key has a particular validation error message. When doing so, you may provide the entire message or only a small portion of the message:

response.assertInvalid({
  name: 'The name field is required.',
  email: 'valid email address',
});
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.