LaraflareDocsFrameworkPackagesReleases13.x

Docs / Testing / Mocking

Mocking

Introduction

When testing laraflare applications, you may wish to "mock" certain aspects of your application so they are not actually executed during a given test. For example, when testing a controller that dispatches an event, you may wish to mock the event listeners so they are not actually executed during the test. This allows you to only test the controller's HTTP response without worrying about the execution of the event listeners since the event listeners can be tested in their own test case.

laraflare provides helpful methods for mocking events, jobs, and other facades out of the box. These helpers primarily provide a convenience layer over Mockery, which laraflare exports from @laraflare/framework/testing, so you do not have to manually make complicated Mockery method calls.

Mocking Objects

When mocking an object that is going to be injected into your application via laraflare's service container, you will need to bind your mocked instance into the container as an instance binding. This will instruct the container to use your mocked instance of the object instead of constructing the object itself:

import { Mockery, type MockObject } from '@laraflare/framework/testing';
import { Service } from '../../app/Service';
import { test } from '../Pest';

test('something can be mocked', function () {
  this.instance(
    Service,
    Mockery.mock(Service, (mock: MockObject<Service>) => {
      mock.expects('process');
    }),
  );
});

In order to make this more convenient, you may use the mock method that is provided by laraflare's base test case class. For example, the following example is equivalent to the example above:

import type { MockObject } from '@laraflare/framework/testing';
import { Service } from '../../app/Service';

const mock = this.mock(Service, (mock: MockObject<Service>) => {
  mock.expects('process');
});

You may use the partialMock method when you only need to mock a few methods of an object. The methods that are not mocked will be executed normally when called:

import type { MockObject } from '@laraflare/framework/testing';
import { Service } from '../../app/Service';

const mock = this.partialMock(Service, (mock: MockObject<Service>) => {
  mock.expects('process');
});

Similarly, if you want to spy on an object, laraflare's base test case class offers a spy method as a convenient wrapper around the Mockery.spy method. Spies are similar to mocks; however, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the code is executed:

import { Service } from '../../app/Service';

const spy = this.spy(Service);

// ...

spy.shouldHaveReceived('process');

Mocking Facades

Unlike traditional static method calls, facades may be mocked. This provides a great advantage over traditional static methods and grants you the same testability that you would have if you were using traditional dependency injection. When testing, you may often want to mock a call to a laraflare facade that occurs in one of your controllers. For example, consider the following controller action:

import { Cache } from '@laraflare/framework';

export default class UserController extends Controller {
  /**
   * Retrieve a list of all users of the application.
   */
  async index(): Promise<unknown[]> {
    const value = await Cache.get('key');

    return [
      // ...
    ];
  }
}

We can mock the call to the Cache facade by using the expects method, which will return a Mockery expectation. Since facades are actually resolved and managed by the laraflare service container, they have much more testability than a typical static class. For example, let's mock our call to the Cache facade's get method:

import { Cache } from '@laraflare/framework';
import { test } from '../Pest';

test('get index', async function () {
  Cache.expects('get')
    .with('key')
    .andReturn('value');

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

  // ...
});

Note

A mocked facade is put back when the test ends, as Mockery.close() runs in the test case's tearDown. So is a facade's fake (Notification.fake(), Mail.fake(), Queue.fake(), Bus.fake(), Event.fake(), Http.fake(), Storage.fake(), Process.fake()): the next test has the real service, as it has in a new application.

Note

laraflare has no real-time facades, so only the facades the framework provides, and the ones you define yourself, may be mocked this way.

Warning

You should not mock the Request facade. Instead, pass the input you desire into the HTTP testing methods such as get and post when running your test. Likewise, instead of mocking the Config facade, call the Config.set method in your tests.

Facade Spies

If you would like to spy on a facade, you may call the spy method on the corresponding facade. Spies are similar to mocks; however, spies record any interaction between the spy and the code being tested, allowing you to make assertions after the code is executed. The spy method returns the spy, so the assertions are made on it:

import { Cache } from '@laraflare/framework';
import { test } from '../Pest';

test('values are stored in cache', async function () {
  const cache = Cache.spy()!;

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

  response.assertStatus(200);

  cache.shouldHaveReceived('put').with('name', 'Taylor', 10);
});

Interacting With Time

When testing, you may occasionally need to modify the time returned by helpers such as now or Carbon.now(). Thankfully, laraflare's base feature test class includes helpers that allow you to manipulate the current time:

import { now } from '@laraflare/framework';
import { test } from '../Pest';

test('time can be manipulated', function () {
  // Travel into the future...
  this.travel(5).milliseconds();
  this.travel(5).seconds();
  this.travel(5).minutes();
  this.travel(5).hours();
  this.travel(5).days();
  this.travel(5).weeks();
  this.travel(5).years();

  // Travel into the past...
  this.travel(-5).hours();

  // Travel to an explicit time...
  this.travelTo(now().minus({ hours: 6 }));

  // Return back to the present time...
  this.travelBack();
});

You may also provide a closure to the various time travel methods. The closure will be invoked with time frozen at the specified time. Once the closure has executed, time will resume as normal:

this.travel(5).days(function () {
  // Test something five days into the future...
});

this.travelTo(now().minus({ days: 10 }), function () {
  // Test something during a given moment...
});

The freezeTime method may be used to freeze the current time. Similarly, the freezeSecond method will freeze the current time but at the start of the current second:

import type { CarbonInterface } from '@laraflare/framework';

// Freeze time and resume normal time after executing closure...
this.freezeTime(function (time: CarbonInterface) {
  // ...
});

// Freeze time at the current second and resume normal time after executing closure...
this.freezeSecond(function (time: CarbonInterface) {
  // ...
});

As you would expect, all of the methods discussed above are primarily useful for testing time sensitive application behavior, such as locking inactive posts on a discussion forum:

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

test('forum threads lock after one week of inactivity', async function () {
  const thread = await Thread.factory().create();

  this.travel(1).week();

  expect(thread.isLockedByInactivity()).toBeTrue();
});
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.