Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass query arguments in graphql-tool?

I am using graphql-tool to mock up data for testing.

I hope to simulate when I select a user, it opens a detail page and shows the user company info.

Query

const query = `
  query User($id: ID!) {
    user(id: $id) {
      id
      company
    }
  }
`;

Mock server

import { addMockFunctionsToSchema } from 'graphql-tools';
import casual from 'casual';

const allUserIds = ['u1', 'u2', 'u3'];

const mocks = {
  User: () => ({
    id: casual.random_element(allUserIds),
    name: casual.name,
    company: casual.company_name
  })
};

addMockFunctionsToSchema({ schema, mocks });

However, right now, when I query with argument id 'u1', it will return a random user id for example 'u2', which gives me a little trouble to show it in front end.

I thought I can do something like this below, but turns out I am wrong. user is undefined in the code below.

const mocks = {
  User: (user) => ({
    id: user.id || casual.random_element(allUserIds),
    name: casual.name,
    company: casual.company_name
  })
};

Is there a way to pass the query arguments in graphql-tools? Thanks

like image 899
Hongbo Miao Avatar asked Jan 29 '19 00:01

Hongbo Miao


1 Answers

It depends on how consistent you want the test data to be. If all you care about is that the id remains consistent with your query argument, here is what you can do:

const mocks = {
  Query: () => ({
    user: (root, user) => ({
      id: user.id || casual.random_element(allUserIds),
      name: casual.name,
      company: casual.company_name
    })
  })
};

As mentioned here in the documentation, mock functions are just like GraphQL resolvers. So the parameters of the functions follow the same order of root, arguments, context that are available for each field.

Please see the code sandbox here for a live demo.

This guarantees whenever you query user with id u1, you always receive a user data object with its id = "u1" with randomly generated company and name fields. However, if you want the entire user object to be persistent throughout a test, you'll need to create the mock user data outside mock functions and query and filter out data accordingly.

like image 144
Claire Lin Avatar answered Nov 10 '22 18:11

Claire Lin