Lighthouse GraphQL PHPUnit Test

I’ll admit. I’m out of practice with unit testing. We don’t really have a good setup db/seeding wise and making a crap ton of factories just took up a lot of time. Not to mention we use GraphQL which I didn’t get how to write a unit test for. Well today, I found out after some quick digging.

Today, I have a new area in our CMS that generates Oauth tokens for Users. To test it I had to generate a temporary user and from there, it was pretty easy (once I realized how everything got returned. I run to asserts. One to make sure the accessToken got returned. Next was the token got set with the user id and name.

Here’s the GraphQL setup:

type Token {
  id: ID!
  client_id: Int
  name: String
  user_id: String!
  revoked: Boolean
  created_at: DateTime!
  updated_at: DateTime!
  expires_at: DateTime!
}

type AccessToken {
  accessToken: String
  token: Token
}

input CreateTokenInput {
  user_id: String!
  name: String!
}

type Mutation {
  createToken(input: CreateTokenInput!): AccessToken @field(resolver: "App\\Models\\User@createUserToken")
}

Now the createUserToken simply returns the new token. Here’s the test.

/**
 * Test that a user can generate a token with GraphQL
 */
public function testUserTokenCreate() {
  // Temporary user to test against.
  $user = factory(User::class)->create(['email' => '']);
  $user->save();
  $name = 'Unit Testing';

  // Builds the query string.
  $query = '
        mutation {
          createToken(input: {user_id: "'.$user->id.'", name: "'.$name.'"} ) {
            accessToken
            token {
              name
              user_id
            }
          }
        }
    ';
  // withApiAuth passes in a helper that gets you authenticated. 
  $response = $this->withApiAuth()
    ->json('POST', '/graphql', [
      'query' => $query
  ]);
  
  // Test that the important bits are included.
  $response->assertJsonStructure([
    'data' => [
        'createToken' => [
            'accessToken',
            'token'
        ],
    ],
  ]);
   
  // Test that things are set right.
  $response->assertJson([
    'data' => [
        'createToken' => [
            'token' => [
              'name' => $name,
              'user_id' => $user->id,
            ]
        ],
    ],
  ]);
}

And viola! Always nice to see the green test lights at theend of the day.