{"id":14976116,"url":"https://github.com/easygraphql/easygraphql-tester","last_synced_at":"2025-04-04T06:06:49.956Z","repository":{"id":37382228,"uuid":"144654952","full_name":"EasyGraphQL/easygraphql-tester","owner":"EasyGraphQL","description":"Test GraphQL queries, mutations and schemas on an easy way! 🚀","archived":false,"fork":false,"pushed_at":"2021-10-06T16:14:35.000Z","size":1283,"stargazers_count":314,"open_issues_count":14,"forks_count":34,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-04T05:51:29.758Z","etag":null,"topics":["graphql","graphql-schema","graphql-tools"],"latest_commit_sha":null,"homepage":"https://easygraphql.com/docs/easygraphql-tester/overview","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/EasyGraphQL.png","metadata":{"files":{"readme":"README.MD","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-08-14T01:54:49.000Z","updated_at":"2024-10-30T13:50:56.000Z","dependencies_parsed_at":"2022-08-03T02:30:14.091Z","dependency_job_id":null,"html_url":"https://github.com/EasyGraphQL/easygraphql-tester","commit_stats":null,"previous_names":[],"tags_count":59,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EasyGraphQL%2Feasygraphql-tester","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EasyGraphQL%2Feasygraphql-tester/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EasyGraphQL%2Feasygraphql-tester/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/EasyGraphQL%2Feasygraphql-tester/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/EasyGraphQL","download_url":"https://codeload.github.com/EasyGraphQL/easygraphql-tester/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247128750,"owners_count":20888235,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphql","graphql-schema","graphql-tools"],"created_at":"2024-09-24T13:53:20.358Z","updated_at":"2025-04-04T06:06:49.922Z","avatar_url":"https://github.com/EasyGraphQL.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003e\n  \u003cimg src=\"https://raw.githubusercontent.com/EasyGraphQL/easygraphql-now/master/logo.png\" alt=\"EasyGraphQL Mock \" width=\"350\"\u003e\n  \u003cbr\u003e\n    easygraphql-tester\n  \u003cbr\u003e\n  \u003cbr\u003e\n\u003c/h1\u003e\n\n[![Coverage Status](https://coveralls.io/repos/github/EasyGraphQL/easygraphql-tester/badge.svg?branch=master)](https://coveralls.io/github/EasyGraphQL/easygraphql-tester?branch=master) [![Greenkeeper badge](https://badges.greenkeeper.io/EasyGraphQL/easygraphql-tester.svg)](https://greenkeeper.io/)\n\n[`easygraphql-tester`](https://github.com/EasyGraphQL/easygraphql-tester) is node library created to make GraphQL tests based on the schema; it's used\nto test the queries, mutations and schema on the easiest way possible.\n\nIt will check:\n+ If the  query/mutation/subscription is defined on the schema.\n+ If the requested fields are defined.\n+ If the arguments are valid.\n+ If the input on a mutation is valid.\n+ If the union is valid.\n+ And much more....\n\n## Installation\n\nTo install the package on your project just run on the root of your project\n```shell\n$ npm install easygraphql-tester --save-dev\n```\n\n[`easygraphql-tester`](https://github.com/EasyGraphQL/easygraphql-tester) can be used in two ways; the first one is using `.tester` as an assertion of the query/mutation, and the second one is using `.mock` to return the mocked query/mutation.\n\n## How to use it?\n\n+ Import [`easygraphql-tester`](https://github.com/EasyGraphQL/easygraphql-tester) package.\n+ Read the schema.\n+ Initialize the tester, and pass the schema as an argument.\n  + If there are multiples schemas pass an array with the schemas an argument.\n  + **Note**: In order to use multiples schema files, the queries and mutations must be extended.\n\n\n### One schema file\n```js\n'use strict' \n\nconst EasyGraphQLTester = require('easygraphql-tester')\nconst fs = require('fs')\nconst path = require('path')\n\nconst userSchema = fs.readFileSync(path.join(__dirname, 'schema', 'user.gql'), 'utf8')\n\nconst tester = new EasyGraphQLTester(userSchema)\n```\n\n### Multiples schemas files\n```js\n'use strict' \n\nconst EasyGraphQLTester = require('easygraphql-tester')\nconst fs = require('fs')\nconst path = require('path')\n\nconst userSchema = fs.readFileSync(path.join(__dirname, 'schema', 'user.gql'), 'utf8')\nconst familySchema = fs.readFileSync(path.join(__dirname, 'schema', 'family.gql'), 'utf8')\n\nconst tester = new EasyGraphQLTester([userSchema, familySchema])\n```\n\n### Using GraphQL.js\n```js\n'use strict'\n\nconst { GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql')\nconst EasyGraphQLTester = require('easygraphql-tester')\n\nconst schema = new GraphQLSchema({\n  query: new GraphQLObjectType({\n    name: 'RootQueryType',\n    fields: {\n      hello: {\n        type: GraphQLString,\n        resolve() {\n          return 'world';\n        }\n      }\n    }\n  })\n});\n\nconst tester = new EasyGraphQLTester(schema)\n```\n\n## Resolvers\n\nTo test GraphQL resolvers, there is something extra to do in case you are not using graphql-js.\nThis is going to be `async`.\n\n### Without graphql-js\nIf you are not using graphql-js, you might pass the resolvers as second argument to the\nconstructor in order to test the resolvers.\n\n```js\n'use strict' \n\nconst EasyGraphQLTester = require('easygraphql-tester')\nconst fs = require('fs')\nconst path = require('path')\n\nconst resolvers = require('./resolvers')\nconst userSchema = fs.readFileSync(path.join(__dirname, 'schema', 'user.gql'), 'utf8')\n\nconst tester = new EasyGraphQLTester(userSchema, resolvers)\n```\n\n### Testing the resolvers\n\nAfter you initializate the class, you can use the method `graphql` and it'll receive\n4 arguments, the only one that is required is the first argument, those arguments are:\n\n+ `query`: The query/mutation you want to test.\n+ `rootValue`: It's going to be the rootValue to pass to the resolver.\n+ `contextValue`: It's going to be the context to pass to the resolver.\n+ `variableValues`: It's going to be the variables that the query/mutation are going to use.\n\n```js\n'use strict' \n\nconst EasyGraphQLTester = require('easygraphql-tester')\n\nconst schema = `\n  type FamilyInfo {\n    id: ID!\n    isLocal: Boolean!\n  }\n\n  type Query {\n    getFamilyInfoByIsLocal(isLocal: Boolean!): FamilyInfo\n  }\n`\n\nconst query = `\n  query TEST($isLocal: Boolean!) {\n    getFamilyInfoByIsLocal(isLocal: $isLocal) {\n      id\n      isLocal\n    }\n  }\n`\n\nfunction getFamilyInfoByIsLocal(__, args, ctx) {\n  return {\n    id: 1,\n    isLocal: args.isLocal\n  }\n}\n\nconst resolvers = {\n  Query: {\n    getFamilyInfoByIsLocal    \n  }\n}\n\nconst tester = new EasyGraphQLTester(schema, resolvers)\n\ntester.graphql(query, undefined, undefined, { isLocal: false })\n  .then(result =\u003e console.log(result))\n  .catch(err =\u003e console.log(err))\n\n// result\n// {\n//   \"data\": {\n//     \"getFamilyInfoByIsLocal\": {\n//       \"id\": \"1\",\n//       \"isLocal\": false\n//     }\n//   }\n}\n```\n\n## Assertion\n\n[`easygraphql-tester`](https://github.com/EasyGraphQL/easygraphql-tester) works as an assertion library used to make tests **with your favorite test runner**.\n\nTo use it as an assertion library, you must follow the next steps:\n\n+ Define a Query or Mutation to test.\n+ Pass as first argument, a boolean to `.test(true)` or `.test(false)`.\n  + true: if it is fine, everything should work fine.\n  + false: if it should fail, there is an error or invalid field on the query/mutation or arguments/input.\n+ Pass as second argument, the query/mutation to test.\n+ The third argument is required **if it is a mutation**, it must be an object with the fields of the input\n\nThe next example is going to be made with mocha, but it can be done **with your favorite test runner**. \n\n### Mocha example\n```js\n'use strict'\n\nconst fs = require('fs')\nconst path = require('path')\nconst EasyGraphQLTester = require('../lib')\n\nconst userSchema = fs.readFileSync(path.join(__dirname, 'schema', 'user.gql'), 'utf8')\nconst familySchema = fs.readFileSync(path.join(__dirname, 'schema', 'family.gql'), 'utf8')\n\ndescribe('Test my queries, mutations and subscriptions', () =\u003e {\n  let tester\n\n  before(() =\u003e {\n    tester = new EasyGraphQLTester([userSchema, familySchema])\n  })\n\n  describe('Should pass if the query is invalid', () =\u003e {\n    it('Invalid query getUser', () =\u003e {\n      const invalidQuery = `\n        {\n          getUser {\n            id\n            invalidField\n            familyInfo {\n              father {\n                email\n                username\n              }\n            }\n          }\n        }\n      `\n      // First arg: false, there is no invalidField on the schema.\n      tester.test(false, invalidQuery)\n    })\n\n    it('Should pass if the query is valid', () =\u003e {\n      const validQuery = `\n        {\n          getMeByTestResult(result: 4.9) {\n            email\n          }\n        }\n      `\n      tester.test(true, validQuery)\n    })\n\n    it('Should pass if the mutation is valid', () =\u003e {\n      const mutation = `\n        mutation UpdateUserScores($scores: ScoresInput!) {\n          updateUserScores(scores: $scores) {\n            email\n            scores\n          }\n        }\n      `\n      tester.test(true, mutation, {\n        scores: {\n          scores: [1, 2, 3]\n        }\n      })\n    })\n\n    it('Should not pass if one value on the mutation input is invalid', () =\u003e {\n      const mutation = `\n        mutation UpdateUserScores($scores: ScoresInput!) {\n          updateUserScores(scores: $scores) {\n            email\n            scores\n          }\n        }\n      `\n      // First arg: false, there is no invalidField on the schema.\n      tester.test(false, mutation, {\n        scores: {\n          scores: [1],\n          invalidField: true\n        }\n      })\n    })\n\n    it('Should search', () =\u003e {\n      const query = `\n        {\n          search(id: \"1\") {\n            ... on User {\n              id\n            }\n            ... on FamilyInfo {\n              id\n              father {\n                username\n              }\n              brothers {\n                username\n              }\n            }\n          }\n        }\n      `\n\n      tester.test(true, query)\n    })\n\n    it('Should test a subscription', () =\u003e {\n      const subscription = `\n        subscription {\n          newUsers(limit: 1) {\n            id\n            username\n            email\n          } \n        }\n      `\n\n      tester.test(true, subscription)\n    })\n  })\n})\n```\n\n## Mocking Queries and Mutations\n\n[`easygraphql-tester`](https://github.com/EasyGraphQL/easygraphql-tester) can works as a mocker of your query or mutation, using it is simple.\n\nCall the method `.mock()` and pass an object with this options:\n\n+ query: It'll be the query/mutation to test.\n+ variables: This is required **if it is a mutation**, it must be an object with the fields of the input.\n+ fixture: This is optional, it'll be an object with the key `data` and inside it\n  the name of the query/mutation/subscription and the fields to set.\n+ saveFixture: By default is `false`, if you pass fixtures, and set it to `true` when you make the same query again,\n  it will return the fixture value.\n+ validateDeprecated: If you want to validate if the query is requesting a deprecated field, set this option to `true`\n  and it'll return an error if a field is deprecated.\n+ mockErrors: If you want to mock the errors instead of throwing it, set this option to `true` and now, the responsw will have\n  `{ data: ..., errors: [...] }`\n\nThe result will have top level fields, it means that the result will be an object\nwith a property that is going to be `data` and inside it the name (top level field) \nof the query or alias with the mocked result.\n\n*In case you have a custom scalar, set the value on the fixture, if it's not set it will be `{}`*\n\n### Fixtures:\n\nThere are two ways to set the fixture on a operation:\n\n#### Operation options:\nSet the fixture as an option when testing a query/mutation/subscription\n\nE.g\n```js\nconst fixture = {\n  data: {\n    getUser: {\n      id: '1',\n      name: 'EasyGraphQL'\n    }\n  }\n}\n\nconst { data: { getUser } } = tester.mock({ query, fixture })\n```\n\n#### `setFixture()` method\nAlso, the fixture can be set before the test using `.setFixture()` method from the constructor,\nit'll receive two arguments; the first one is going to be the fixture, and the second one will be\nan object of options to set if it should auto mock the extra fields that are on the query but are not\non the fixture, by default it's `true`.\n\nRun `tester.clearFixture()` to return the fixture to `null` and `autoMock = true` in case you\nset it to `false`\n\nE.g\n```js\nconst tester = new EasyGraphQLTester([userSchema, familySchema])\n\nconst fixture = {\n  data: {\n    getUser: {\n      id: '1',\n      name: 'EasyGraphQL'\n    }\n  }\n}\n\ntester.setFixture(fixture, { autoMock: false })\nconst { data: { getUser } } = tester.mock({ query })\ntester.clearFixture()\n```\n\n### Mock example\n```js\n'use strict'\n\nconst EasyGraphQLTester = require('easygraphql-tester')\nconst fs = require('fs')\nconst path = require('path')\n\nconst userSchema = fs.readFileSync(path.join(__dirname, 'schema', 'user.gql'), 'utf8')\nconst familySchema = fs.readFileSync(path.join(__dirname, 'schema', 'family.gql'), 'utf8')\n\nconst tester = new EasyGraphQLTester([userSchema, familySchema])\n\nconst query = `\n  {\n    getUser(id: \"1\") {\n      id\n      name\n      familyInfo {\n        lastName\n        email\n      }\n    }\n  }\n`\n\nconst fixture = {\n  data: {\n    getUser: {\n      id: '1',\n      name: 'EasyGraphQL'\n    }\n  }\n}\n\nconst { data: { getUser } } = tester.mock({ query, fixture, validateDeprecated: true })\nconst { errors } = tester.mock({ \n  query, \n  fixture: {\n    errors: [\n      {\n        \"message\": \"Cannot query field \\\"invalidField\\\" on type \\\"FamilyInfo\\\".\",\n        \"locations\": [\n          {\n            \"line\": 7,\n            \"column\": 5\n          }\n        ]\n      }\n    ]\n  }\n})\n\nconst queryWithAlias = `\n  {\n    firstUser: getUser(id: \"1\") {\n      id\n    }\n  }\n`\nconst { data: { firstUser } } = tester.mock({ query: queryWithAlias })\n\n\nconst mutation = `\n  mutation CreateUser($input: CreateUserInput!) {\n    createUser(input: $input) {\n      id\n      name\n    }\n  }\n`\nconst input = {\n  input: {\n    name: 'test'    \n  }\n}\n\nconst { data: { createUser } } = tester.mock({ query: mutation, variables: input })\n```\n\n### Mock result\n```js\n// getUser\n{ \n  id: '1',\n  name: 'EasyGraphQL',\n  familyInfo: [\n    { \n      lastName: 'Bartoletti',\n      email: 'YSjsYuV@wtnK.com'\n    },\n    { \n      lastName: 'Bartoletti',\n      email: 'YSjsYuV@wtnK.com'\n    },\n    { \n      lastName: 'Bartoletti',\n      email: 'YSjsYuV@wtnK.com'\n    }\n  ]\n}\n\n// errors\n{\n  [\n    {\n      \"message\": \"Cannot query field \\\"invalidField\\\" on type \\\"FamilyInfo\\\".\",\n      \"locations\": [\n        {\n          \"line\": 7,\n          \"column\": 5\n        }\n      ]\n    }\n  ]\n}\n\n//firstUser\n{\n  id: '93'\n}\n\n\n// createUser\n{\n  id: '93',\n  name: 'Tony Patrick'\n}\n```\n\n## Demo\nHere is a [Demo](https://codesandbox.io/embed/42m2rx71j4?previewwindow=tests\u0026view=preview) that can be useful!\n\n# License\n### The MIT License\n\nCopyright (c) 2018 EasyGraphQL\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feasygraphql%2Feasygraphql-tester","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feasygraphql%2Feasygraphql-tester","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feasygraphql%2Feasygraphql-tester/lists"}