What is Pest?
Pest is a testing framework for PHP that provides a simple and intuitive way to write tests for our code. It's designed to be fast, flexible, and easy to use.
Why use Pest?
We should use Pest because it makes it easy to write tests for our code, which helps to ensure that our code works correctly and catches bugs early. Pest is also fast and flexible, making it a great choice for large and small projects alike.
Where to use Pest in a project?
We can use Pest in any PHP project, big or small. It's a great tool for testing individual components, such as classes or functions, as well as larger systems, such as APIs or web applications. We can use Pest in the tests
directory of our project, alongside our code.
Some common use cases for Pest include:
- Unit testing: Test individual components, such as classes or functions, to ensure they work correctly.
- Feature testing: Test multiple tests in a single file in a project.
- Integration testing: Test larger systems, such as APIs or web applications, to ensure they work correctly.
- Acceptance testing: Test your code against a set of acceptance criteria to ensure it meets the requirements.
Test Implementation
To test either the user is logged in or not, create a new file AuthenticatorTest.php
and add this code:
<?php
use Core\Authenticator;
test('user is logged in or not', function () {
if ($_Session['user']) {
$_SESSION['user'] = ['email' => 'mujtabaofficial247@gmail.com'];
} else {
unset($_SESSION['user']);
}
// Create an instance of the Authenticator class
$auth = new Authenticator();
// Test if the user is logged in or not
expect($auth->isLoggedIn())->toBeFalse();
});
This test code checks if the Authenticator
class is working correctly. It sets up the $_SESSION
superglobal and then creates an instance of the Authenticator
class. Finally, it uses Pest's expect
function to assert that the isLoggedIn
method returns false
when the user is not logged in.
Helper Function
To test user loggedIn or Out add isLoggedIn
method in Authenticator class as:
public function isLoggedIn() {
return isset($_SESSION['user']) && !empty($_SESSION['user']);
}
This helper function checks if a user is logged in by verifying if the $_SESSION['user']
variable is set and not empty.
Running Tests in Terminal
To run this test, we would use the command php vendor/bin/pest
in your terminal. This command runs all tests in the tests
directory.
Running Specific Test File
If you want to run a specific test file, you can use the command pest test/Unit/AuthenticatorTest.php
. This command runs only the tests in the specified file.
Top comments (0)