Jest example in PHP
Jest is a JavaScript testing framework and cannot be run natively within PHP. The standard and most popular tool for unit testing PHP code is PHPUnit.
If your goal is to test the client-side JavaScript that is part of a PHP project, you can use Jest to test that JavaScript code specifically.
Testing JavaScript in a PHP Project with Jest
Here is an example of how to test JavaScript code using Jest in a project that also uses PHP.
1. Setup Your Project
You need Node.js and npm installed. Navigate to your project root in the terminal and run:
npm init -y
npm install --save-dev jest
Update your
package.json file to include a test script: {
"name": "your-php-project",
"version": "1.0.0",
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^29.7.0"
}
}
2. The JavaScript Code (math.js)
Create a JavaScript file with a simple function you want to test.
// math.js
function sum(a, b) {
return a + b;
}
module.exports = { sum };
3. The Jest Test File (math.test.js)
Create a test file in the same directory, usually with a
.test.js or .spec.js extension. // math.test.js
const { sum } = require('./math.js');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
4. Run the Test
Run the tests using the command you defined in
package.json: npm test
Alternative: Testing Server-Side PHP with PHPUnit
For testing the actual PHP backend logic (e.g., classes, database interactions), the idiomatic and official testing framework is PHPUnit.
PHP Example with PHPUnit
- Install PHPUnit via Composer:
composer require --dev phpunit/phpunit - PHP Code (e.g.,
src/User.php):// src/User.php class User { public function getFullName(string $firstName, string $lastName): string { return $firstName . ' ' . $lastName; } } - PHPUnit Test (e.g.,
tests/UserTest.php):// tests/UserTest.php use PHPUnit\Framework\TestCase; class UserTest extends TestCase { public function testGetFullName() { $user = new User(); $result = $user->getFullName('Jane', 'Doe'); $this->assertSame('Jane Doe', $result); } } - Run PHPUnit from the command line after setting up your
autoload.phpandphpunit.xmlconfiguration file:./vendor/bin/phpunit tests/UserTest.php
For PHP testing, the PHPUnit documentation is the best resource, while the Jest documentation covers JavaScript testing.