How may I test in CakePHP with Pest

300 views Asked by At

My problem: How my I test some MVC part with Pest in CakePHP, for example: When I´m use PHPUnit, I´ll type:

public class ItemTest extends TestCase

And it will show what thing that I wanna test, but how do that with Pest?

(Obs.: I´m really new on tests, so I accept anything that will make me improve :) )

1

There are 1 answers

1
Theraloss On

After you installed Pest you just have to follow its syntax and documentation, removing all the OOP code and just using test() or it(). The file name will be the same. This is an example from CakePHP docs:

class ArticlesTableTest extends TestCase
{
    public $fixtures = ['app.Articles'];

    public function setUp()
    {
        parent::setUp();
        $this->Articles = TableRegistry::getTableLocator()->get('Articles');
    }

    public function testFindPublished()
    {
        $query = $this->Articles->find('published');
        $this->assertInstanceOf('Cake\ORM\Query', $query);
        $result = $query->enableHydration(false)->toArray();
        $expected = [
            ['id' => 1, 'title' => 'First Article'],
            ['id' => 2, 'title' => 'Second Article'],
            ['id' => 3, 'title' => 'Third Article']
        ];

        $this->assertEquals($expected, $result);
    }
}

With Pest, it will become:

beforeEach(function () {
    $this->Articles = TableRegistry::getTableLocator()->get('Articles');
});

test('findPublished', function () {
    $query = $this->Articles->find('published');

    expect($query)->toBeInstanceOf('Cake\ORM\Query');

    $result = $query->enableHydration(false)->toArray();
    $expected = [
        ['id' => 1, 'title' => 'First Article'],
        ['id' => 2, 'title' => 'Second Article'],
        ['id' => 3, 'title' => 'Third Article']
    ];

    expect($result)->toBe($expected);
});

Note that toBeInstanceOf() and toBe() are part of the available Pest expectations.

Finally, instead of running your test suite with $ ./vendor/bin/phpunit, you will run it with $ ./vendor/bin/pest.