How do you guys write the graphql test? You can define a query and test it, but it's a bit annoying these days. Therefore, I will explain how to test the resolver defined in query or mutation with rspec.
For example, let's say you have defined the following mutation.
mutation.rb
module Mutations
class CreateUser < BaseMutation
argument :id, ID, required: true
field :user, ObjectTypes::UserType, null: false
def resolve(id: nil)
user = ::User.create!(id: id)
{
user: user
}
end
end
end
It's simple, but it's a mutation that gets an id and creates a user. The target of this test is this resolve.
Now I want to write rspec.
create_user_rspec.rb
require 'rails_helper'
RSpec.describe CreateUser, type: :request do
describe 'resolver' do
it 'user has been created' do
mutation = CreateUser.new(field: nil, object: nil, context:{})
mutation.resolve(id: [User to create_id])
expect(..).to eq ..
end
First, create an instance of the CreateUser
class, which is a mutation class.
I think that the argument field and object can basically be null.
For context, you can also include current_user
in some cases. In that case, it will be context: {current_user: User.first}
.
It's convenient to be able to enter the context directly. Then, if you read the resolve method of the created mutation, the processing in the resolve defined on the test will be executed. This makes graphql testing a lot easier!
Recommended Posts