I have a user creator Livewire component which has a profile picture uploader. Trying to write some the unit tests for the File field of that form, but it doesn’t want to work. I’m sure that my approach is wrong, but there is no other way documented, with which I can achieve what I want.
So I have these fields:
public array $state = [
'full_name' => null,
'email' => null,
'password' => null,
'password_confirmation' => null,
'verified' => false,
'profile_picture' => null,
'permissions' => [],
'roles' => []
];
with these validation rules
protected $rules = [
'state.full_name' => 'required',
'state.email' => 'required|email|unique:users,email',
'state.password' => 'required|confirmed|min:6',
'state.password_confirmation' => 'required',
'state.profile_picture' => 'image|max:2048|nullable',
'state.permissions' => 'array',
'state.roles' => 'array'
];
which then uses these messages
public function messages(): array
{
return [
'state.full_name.required' => trans('validation.required', ['attribute' => 'name']),
'state.email.required' => trans('validation.required', ['attribute' => 'email']),
'state.email.unique' => trans('validation.unique', ['attribute' => 'user email']),
'state.email.email' => trans('validation.email', ['attribute' => 'user email']),
'state.password.required' => trans('validation.required', ['attribute' => 'password']),
'state.password.min' => trans('validation.min.string', ['attribute' => 'password', 'min' => 6]),
'state.password.confirmed' => trans('validation.confirmed', ['attribute' => 'password']),
'state.profile_picture.image' => trans('validation.image', ['attribute' => 'profile picture']),
'state.profile_picture.max' => trans('validation.max.file', ['max' => '2048', 'attribute' => 'profile picture'])
];
}
and here is my test
/** @test */
public function fails_with_oversized_profile_image()
{
$this->actingAs($this->userWithAddPermissionAccess);
$this->assertEquals(3, User::count());
$profileImage = UploadedFile::fake()->create('picture.jpg', 432545243254325342543254325);
$profileImageMocked = Mockery::mock($profileImage);
$profileImageMocked
->shouldReceive('temporaryUrl')
->andReturn('http://some-signed-url.test');
Livewire::test(CreateUser::class)
->set('state', [
'full_name' => 'Joe Doe',
'email' => '[email protected]',
'password' => 'password',
'password_confirmation' => 'password',
'profile_picture' => $profileImageMocked,
'permissions' => [],
'roles' => []
])
->call('addUser')
->assertHasErrors(['state.profile_picture' => 'max']);
$this->assertEquals(3, User::count());
}
but the result I’m getting is that ‘Component has no errors.’ .The validator doesn’t find any issue with that mocked File I passed to the component.
Probably I shouldn’t use mocks, but the official documentation suggests the use of the UploadedFile faker, but the object returned by that doesn’t have a temporaryUrl method, which is called by my component and it makes my component fail the test.