Test Dependencies
Sometimes, tests require certain preconditions or events to occur prior to their execution, or else they will not succeed. For example, you may only be able to verify that users are able to modify their accounts once you have first verified that an account can be established.
To address this, Pest offers the depends() method, which allows a "Child" test to specify that it depends on one or more "Parent" tests:
1test('parent', function () {2 expect(true)->toBeTrue();3});4 5test('child', function () {6 expect(false)->toBeFalse();7})->depends('parent');
In this example, the child test will be triggered once the parent test has successfully completed:
If the parent test fails, the child test will be bypassed, and an informative message will be displayed in your test results:
1test('parent', function () {2 expect(true)->toBeFalse();3});4 5test('child', function () {6 expect(false)->toBeFalse();7})->depends('parent');
The example above will result in the following output:
It is important to remember that the it() function prefixes the test with "it" by default. Thus, when referencing the test name via the depends() method, you should include the "it " prefix:
1it('is the parent', function () {2 expect(true)->toBeTrue();3});4 5test('child', function () {6 expect(false)->toBeFalse();7})->depends('it is the parent');
This results in the following output:
Parent tests may even provide return values that can be accessed as arguments in the child test:
1test('parent', function () { 2 expect(true)->toBeTrue(); 3 4 return 'from parent'; 5}); 6 7test('child', function ($parentValue) { 8 var_dump($parentValue); // from parent 9 10 expect($parentValue)->toBe('from parent');11})->depends('parent');
You may also add multiple dependencies to a test. However, all parent tests must pass, and the values returned by each test will be available as function parameters in the same order as the specified dependencies:
1test('a', function () { 2 expect(true)->toBeTrue(); 3 4 return 'a'; 5}); 6 7test('b', function () { 8 expect(true)->toBeTrue(); 9 10 return 'b';11});12 13test('c', function () {14 expect(true)->toBeTrue();15 16 return 'c';17});18 19test('d', function ($testA, $testC, $testB) {20 var_dump($testA); // a21 var_dump($testB); // b22 var_dump($testC); // c23})->depends('a', 'b', 'c');
While test dependencies are uncommon, they can be helpful for optimizing your tests and minimizing the need to recreate resources repeatedly. In the next chapter, we will explore how you may create plugins: Creating Plugins