How can I test the api resource without hitting the database ? , I tried to do the following, but it throws an error.
$user = new User([
'username' => 'Jonh',
'email' => '[email protected]',
'password' => bcrypt('secret'),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
Topic::unguard();
$user->setRelation('topics', [
new Topic([
'id' => 1,
'section_id' => 1,
'user_id' => 1,
'body' => 'Test post',
'title' => 'something',
'slug' => 'donoqwdnowq',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
])
]);
$resource = (new UserResource($user))->toArray(request());
$this->assertEquals(['username','email','avatar','topics'], array_keys($resource));
Here is the UserResource
public function toArray($request) {
return [
'username' => $this->username,
'email' => $this->email,
'avatar' => $this->avatar(),
'topics' => new TopicResource($this->whenLoaded('topics'))
];
}
and Topic Resource
public function toArray($request) {
return [
'title' => $this->title,
'slug' => $this->slug,
'body' => $this->body,
'diffForHumans' => $this->created_at->diffForHumans(),
'user' => new UserResource($this->user),
'section' => new SectionResource($this->whenLoaded('section')),
'comments' => CommentResource::collection($this->whenLoaded('comments')),
];
}
Error :
E 1 / 1 (100%)
Time: 2.44 seconds, Memory: 18.00MB
There was 1 error:
1) Tests\Unit\Users\Domain\Resources\UserResourceTest::it_returns_posts_associated_with_user_on_loading
ErrorException: Trying to get property 'title' of non-object
/Users/mohammed/projects/cross-api/vendor/laravel/framework/src/Illuminate/Http/Resources/DelegatesToResource.php:120
/Users/mohammed/projects/cross-api/app/Forum/Domain/Resources/TopicResource.php:19
/Users/mohammed/projects/cross-api/tests/Unit/Users/Domain/Resources/UserResourceTest.php:54
Note: it worked well when I wasn't passing something to load like topics, I think there is just a problem with loading nested resources but I don't know how to tweak it around.