Skip to main content

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: 

bash
npm init -y
npm install --save-dev jest
Update your package.json file to include a test script: 

json
{
  "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. 

javascript
// 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. 

javascript
// 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: 

bash
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
  1. Install PHPUnit via Composer:
    bash
    composer require --dev phpunit/phpunit
    
  2. PHP Code (e.g., src/User.php):
    php
    // src/User.php
    class User
    {
        public function getFullName(string $firstName, string $lastName): string
        {
            return $firstName . ' ' . $lastName;
        }
    }
    
  3. PHPUnit Test (e.g., tests/UserTest.php):
    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);
        }
    }
    
  4. Run PHPUnit from the command line after setting up your autoload.php and phpunit.xml configuration file:
    bash
    ./vendor/bin/phpunit tests/UserTest.php
    
     
For PHP testing, the PHPUnit documentation is the best resource, while the Jest documentation covers JavaScript testing.