How to use the graphql-tools.mockServer function in graphql-tools

To help you get started, we’ve selected a few graphql-tools examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Kong / mockbin / lib / routes / bins / view_graphql.js View on Github external
//const data = "{'books': [{ 'title': 'blah', 'author': 'blah'},{ 'title': 'what', 'author': 'ever'}]}"
	//const typeDefs = 'type Query { getBooks: [Book], getString: String! } type Book { title: String author: String!}'

	// TEMP nice to see the qury in the window
	console.log("\nQuery:\n" + query);

	var index = 0;
	var d = JSON.parse(value);
	//const mocks = { Books: () => ({ title: JSON.stringify(d.books[index++]), author: "aaaa" }) }
	const mocks = { String: () => casual.sentence, Int: () => casual.integer(0, 10000), Float: () => casual.double(0.1, 10000) }
	//const mocks = utils.mocksFromJSON(value);
        console.log(mocks);

	const preserveResolvers = false
	const server = mockServer(schema, mocks, preserveResolvers);
	const variables = {}

        try {
		server.query(query, variables)
  			.then(function(response){  
      				console.log(response);
      				res.status(200).location('/').body = response;
      				next()
     			})

        } catch(e) {
	
		res.status(500).location('/').body = "{ \"error\" : \"Error mocking server\" }";
		next()
	}
    }
github baianat / vue-gql / test / server / setup.ts View on Github external
import { mockServer, MockList } from 'graphql-tools';
import schema from './schema';

const server = mockServer(schema, {
  Post: () => ({
    id: () =>
      Math.random()
        .toString(36)
        .substring(7),
    title: () => 'Hello World',
    slug: () => 'hello-world'
  }),
  Query: () => ({
    posts: () => new MockList(5),
    post: (_: any, { id }: any) => {
      return {
        id,
        title: `Hello World: ${id}`,
        slug: 'hello-world'
      };
github mrdulin / apollo-server-express-starter / src / mocking / mockServer.spec.js View on Github external
return fakeDB.users.find(user => user.id === id);
      }
    };
  },
  Mutation: () => {
    return {
      updateUserName: (source, { id, name }, context, info) => {
        const userFound = fakeDB.users.find(user => user.id === id);
        userFound.name = name;
        return userFound;
      }
    };
  }
};

const mockserver = mockServer(schema, mocks);

describe('mockServer test suites', () => {
  it('should get users correctly', () => {
    mockserver
      .query(
        `{
        allUsers{
          id
          name
        }
      }`
      )
      .then(res => {
        const users = res.data.allUsers;
        expect(users)
          .to.be.an('array')
github nicky-lenaers / mogr / src / project.spec.ts View on Github external
it('should skip GraphQL TypeName Fields', async () => {

    const tc = simpleCase(connection);
    let projection: string;

    const server = mockServer(tc.schema, {
      SimpleType: (...args) => {
        const info = args[args.length - 1];
        projection = registry.project(info, tc.model.modelName);
        return tc.response;
      }
    });

    await server.query(`
      query simple {
        simple {
          __typename,
          foo,
          bar
        }
      }
    `);
github nicky-lenaers / mogr / src / populate.spec.ts View on Github external
it('should handle complex GraphQL Fields', async () => {

    const tc = complexRefCase(connection);
    let population: ModelPopulateOptions[];

    const server = mockServer(tc.schema, {
      ComplexRefType: (...args) => {
        const info = args[args.length - 1];
        population = registry.populate(info, tc.model.modelName);
        return tc.response;
      }
    });

    await server.query(`
      query complexRef {
        complexRef {
          children {
            child {
              foo,
              bar,
              child {
                foo,
github Coobaha / graphql-to-reason / schema.js View on Github external
async function exportSchema(schemaPath, outputPath) {
  const schema = await readFileAsync(schemaPath, "utf8");
  const result = await mockServer(schema).query(
    graphql.getIntrospectionQuery()
  );
  await writeFileAsync(outputPath, JSON.stringify(result, null, 2), "utf8");
}
github almilo / gql-tools / schema / index.js View on Github external
exports.generateIntrospectedSchema = function (schemaResource, outputFileName) {
    var promise = isUrl(schemaResource) ?
        fetchIntrospectionSchema(schemaResource) :
        mockServer(read(schemaResource)).query(graphql.introspectionQuery);

    writeToFile(promise, 'introspection schema', outputFileName);
};
github nicky-lenaers / mogr / src / pagination / types / page.spec.ts View on Github external
edges: [{
        cursor,
        node: {
          foo: 'Foo',
          bar: 'Bar'
        }
      }],
      pageInfo: {
        startCursor: cursor,
        endCursor: cursor,
        hasPrevPage: false,
        hasNextPage: false
      }
    };

    const server = mockServer(schema, { PaginatedTestType: () => response });

    const res = await server.query(`
      query testPage {
        testPage {
          totalCount,
          edges {
            cursor,
            node {
              foo,
              bar
            }
          },
          pageInfo {
            startCursor,
            endCursor,
            hasPrevPage,
github nicky-lenaers / mogr / src / pagination / types / filter.spec.ts View on Github external
],
      query: new GraphQLObjectType({
        name: 'TestQueries',
        fields: () => ({
          testFilter: {
            type: TestInterfaceType,
            args: {
              filters: { type: FilterType(TestInterfaceType) }
            }
          }
        })
      })
    });

    const response = { foo: 'Foo', bar: 'Bar' };
    const server = mockServer(schema, { TestType: () => response });

    const res = await server.query(`
      query testFilter($filters: [FilterTestInterfaceType]) {
        testFilter(filters: $filters) {
          foo,
          bar
        }
      }
    `, { filters: [{ foo: { eq: 'Foo' }, bar: { eq: 'Bar' } }] });

    expect(res).toEqual({ data: { testFilter: response } });
  });
});