Category : laravel-testing

In my Laravel project I use some MySQL based SQL functions in my queries, like this: Post::whereRaw(‘publish_at < NOW()’); SELECT * FROM posts WHERE publish_at < NOW(); Or this: Post::whereRaw(‘TIMESTAMP(publish_date, publish_time) < NOW()’); SELECT * FROM posts WHERE TIMESTAMP(publish_date, publish_time) < NOW(); These queries works fine with MySQL db, but if I try to test ..

Read more

I just want to test an easy input field but I get this error! /** @test */ public function email_must_be_a_valid_email() { $response = $this->post(‘/api/contacts’, array_merge($this->data(), [’email’ => ‘NOT AN EMAIL’])); $response->assertSessionHasErrors(’email’); } private function data() { return [ ‘name’ => ‘Test Name’, ’email’ => ‘[email protected]’, ‘birthday’ => ’05/14/1988′, ‘company’ => ‘ABC String’ ]; } I ..

Read more

In my Laravel 8 project, I have this action class: <?php namespace AppActionsContent; use IlluminateSupportFacadesConfig; class FixUriAction { public function __invoke(string $uri) { if (preg_match(‘/^https?:///i’, $uri)) { return $uri; } return ‘/’ . Config::get(‘current_lang’)->code . ‘/’ . $uri; } } I want to write unit tests for this class, now I have this code in ..

Read more

From the Laravel Testing Documentation: # Parallel Testing & Databases Laravel automatically handles creating and migrating a test database for each parallel process that is running your tests. The test databases will be suffixed with a process token which is unique per process. For example, if you have two parallel test processes, Laravel will create ..

Read more

My test: class FloorStackTest extends TestCase { use RefreshDatabase, WithFaker, DatabaseMigrations; protected $endPoint = ‘/endpoint’; public function test_unit_type_note_added_successfully() { $this->signIn(); $this->withoutExceptionHandling(); $unitType = UnitType::factory()->create(); $note = $this->faker()->sentence(3); $resp = $this->ajaxPost($this->admin_route.$this->endPoint."/".$unitType->property_version_id."/save-ut-note",[ ‘notes’ => [ [ "ut_note_id" => "utn_".$unitType->id, "note" => $note ] ] ])->assertStatus(Response::HTTP_OK); $results = [ ‘notes’ => $note ]; //i could print upto here ..

Read more

I am trying to test if the filter response has the right JSON data (every item should have the filtered group_code). I tried the following code but it doesn’t work. public function test_filter_items_by_group_code_work_properly() { $filterCode = ‘026’; $response = $this->get($this->ITEMS_URL . ‘?’ . $this->groupAttribute . ‘=’. $filterCode); $response->assertStatus(200); $items = $response->json()[‘data’]; foreach ($items as $item) ..

Read more

My test case: <?php namespace TestsFeature; use IlluminateFoundationTestingRefreshDatabase; use IlluminateFoundationTestingWithFaker; use TestsTestCase; use IlluminateHttpResponse; use IlluminateFoundationTestingDatabaseMigrations; class UserTest extends TestCase { use RefreshDatabase, WithFaker, DatabaseMigrations; protected $endPoint = ‘/dashboard/users’; public function setUp():void { parent::setUp(); $this->artisan(‘migrate:fresh’); $this->artisan(‘db:seed’); } public function test_users_list_is_showing_correctly() { $this->signIn(); $this->get($this->endPoint) ->assertStatus(Response::HTTP_OK); } } But, I am receiving error: SQLSTATE[HY000]: General error: 1 ..

Read more

When i run the command php artisan test and get the following error message i tried assigning my value to a string but it still doesn’t work. Hope someone has a way to fix this error for me. This is my file ClipartTest.php: <?php namespace TestsFeature; use AppModelsClipart; use AppModelsImage; use AppModelsUser; use IlluminateFoundationTestingRefreshDatabase; use ..

Read more

while testing a laravel package with Orchestral/testbench, I’m getting error 500. but the exception handling do not say much why the error happend. here is the TestCase.php <?php namespace DivineAlienGourlTests; use DivineAlienGourlGourlServiceProvider; use OrchestraTestbenchTestCase as Orchestra; abstract class TestCase extends Orchestra { public function setUp(): void { parent::setUp(); } protected function getPackageProviders($app) { return [ ..

Read more

PS C:xampphtdocslaravel_testing> PHP artisan test Warning: TTY mode is not supported on the Windows platform. RUNS TestsUnitAccountantHelperTest • it can find profit Tests: 3 pending FAIL TestsUnitAccountantHelperTest ✕ it can find profit Tests: 1 failed, 2 pending Error Class ‘AppAccountantHelper’ not found at C:xampphtdocslaravel_testingtestsUnitAccountantHelperTest.php:16 12| * @test 13| */ 14| public function it_can_find_profit() 15| { ..

Read more

So in my application I’ve some routes that need special treatment which is why I have something like this: Route::prefix(‘external’)->group(function () { Route::any(Request::path(), ‘[email protected]’); }); Basically every route which is /api/external* goes into that part. Somehow, when I run my feature tests, Request::path() or request()->path() (doesn’t matter) is always / I also tried $_SERVER but ..

Read more

I have a Trait that I use on multiple models in my app for setting a UUID on the model: <?php namespace AppTraits; use IlluminateSupportStr; trait UsesUuid { protected static function bootUsesUuid() { static::creating(function ($model) { if (!$model->uuid) { $model->uuid = (string) Str::orderedUuid(); } }); } } It works fine when using the app normally, ..

Read more

I have a Trait that I use on multiple models in my app for setting a UUID on the model: <?php namespace AppTraits; use IlluminateSupportStr; trait UsesUuid { protected static function bootUsesUuid() { static::creating(function ($model) { if (!$model->uuid) { $model->uuid = (string) Str::orderedUuid(); } }); } } It works fine when using the app normally, ..

Read more

I have defined relationship in the ModelClass public function allocations(): MorphMany { return $this->morphMany( Allocation::class, ‘allocatable’, ‘ref_class’, ‘ref_id’ )->where(‘is_active’, 1); // this line is creating issue } Test Case public function testAllocations(): void { // Arrange $morphMany = $this->partialMock(MorphMany::class); $model = $this->createPartialMock( ModelClass::class, [‘morphMany’] ); // Expectations $model->expects($this->once()) ->method(‘morphMany’) ->with( Allocation::class, ‘allocatable’, ‘ref_class’, ‘ref_id’ ) ..

Read more

Since I am still rather a beginner in Laravel, I just stumbled upon an interesting issue with testing and need a second opinion. I wrote models, controllers, views, factories, seeders and then (feature) tests. Tests do cover a lot (won’t say all), but I just found out an issue which was not caught by tests, ..

Read more

I added a custom setUpBeforeClass() method in my TestCase.php to make sure the testing database exists. Hwoever when running my tests I get an error: Call to a member function connection() on null at vendor/laravel/framework/src/Illuminate/Support/Facades/Schema.php:35 31▕ * @return IlluminateDatabaseSchemaBuilder 32▕ */ 33▕ public static function connection($name) 34▕ { ➜ 35▕ return static::$app[‘db’]->connection($name)->getSchemaBuilder(); 36▕ } 37▕ ..

Read more

I’d like to create a test whether a user can update a model using the api. This is the API-route: Route::apiResource(‘user’, UserApiController::class); This is the test: public function test_user_can_update_user() { $user = User::factory()->create(); Passport::actingAs($user); $this->putJson(‘/api/user/’.$user->id, […])->assertStatus (200); } but unfortunately this returns 404: • TestsFeatureUserTest >user can update user Expected status code 200 but received ..

Read more

I wrote a very simple feature test in Laravel public function must_be_authenticated_to_access_posts() { $response = $this->get(‘/posts’)->assertRedirect(‘/login’); } Which promptly fails because it gets a 404 error instead of a redirect. If I add $this->withoutExceptionHandling(); I can see it is doing a GET request to the wrong domain. It is doing a GET request to http://localhost/project.local/posts ..

Read more