Faking GraphQL with ember-cli-mirage
I’m in the process of replacing ember-data and REST with ember-redux and GraphQL. Everything is clicking wonderfully.
After searching with no luck for something to mock out GraphQL requests for my tests, it occurred to me that I can use mirage to do this. While I don’t need the JSON API serializers and shortcuts that ship with mirage, the factories and Pretender initializers are a great fit.
There is room for a lot of abstraction and improvement, no doubt, but here is how I am doing it at the moment:
First, I set up a user model. It’s important to note that these models have nothing to do with ember data models. This is just a stub so that mirage can set up its internal schema.
Then I create a fixture to serve as a “current” user.
Now I want to handle two GraphQL requests.
The first request is a query for the currently authenticated user. In my implementation that query looks like this:
{
me {
id
email
}
}
The second request is a mutation to register a new user. In my implementation, that query looks like this:
mutation {
registerUser(email: "me@mydomain.org", password: "correct") {
id
}
}
GraphQL requests go to the same endpoint, so handling them involves an if-else-if block. This is my code to handle these requests using mirage:
The trick in the mutation request is to use regex to capture parameters, then leverage mirage’s schema to persist the new record.