{"id":19226991,"url":"https://github.com/dvtng/graphql-automock","last_synced_at":"2025-06-24T06:33:26.580Z","repository":{"id":57253364,"uuid":"140985003","full_name":"dvtng/graphql-automock","owner":"dvtng","description":"Automock GraphQL schemas for better testing","archived":false,"fork":false,"pushed_at":"2018-09-29T00:40:42.000Z","size":81,"stargazers_count":13,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-11T16:09:49.043Z","etag":null,"topics":["apollo","apollo-client","graphql","mock","testing"],"latest_commit_sha":null,"homepage":null,"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/dvtng.png","metadata":{"files":{"readme":"README.md","changelog":null,"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-07-14T23:36:49.000Z","updated_at":"2022-04-12T08:40:03.000Z","dependencies_parsed_at":"2022-08-31T22:20:12.864Z","dependency_job_id":null,"html_url":"https://github.com/dvtng/graphql-automock","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dvtng%2Fgraphql-automock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dvtng%2Fgraphql-automock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dvtng%2Fgraphql-automock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dvtng%2Fgraphql-automock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dvtng","download_url":"https://codeload.github.com/dvtng/graphql-automock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223843711,"owners_count":17212631,"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":["apollo","apollo-client","graphql","mock","testing"],"created_at":"2024-11-09T15:21:15.002Z","updated_at":"2024-11-09T15:21:15.631Z","avatar_url":"https://github.com/dvtng.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ⭐️ graphql-automock ⭐️\n\n**Automatically mock GraphQL schemas for better testing.**\n\nFeatures:\n\n- Automatically and deterministically mock GraphQL schemas\n- Mock `react-apollo` for simple UI testing\n- Control schema execution to reliably test loading and success states\n\n## Getting started\n\nInstall via npm or yarn:\n\n```sh\nnpm install --save-dev graphql-automock\nyarn add --dev graphql-automock\n```\n\n## Mocking just the schema\n\nSimply pass your GraphQL type definitions to `mockSchema` and\nyou're ready to go:\n\n```javascript\nimport { mockSchema } from \"graphql-automock\";\nimport { graphql } from \"graphql\";\n\nconst types = `\n  type Query {\n    recentPosts: [Post!]!\n  }\n\n  type Post {\n    id: ID!\n    content: String!\n    likes: Int!\n  }\n`;\n\nconst mocked = mockSchema(types);\n\nconst query = `{\n  recentPosts {\n    id\n    content\n    likes\n  }\n}`;\n\ngraphql(mocked, query);\n```\n\nWithout any further configuration, this query will return:\n\n```json\n{\n  \"data\": {\n    \"recentPosts\": [\n      {\n        \"id\": \"recentPosts.0.id\",\n        \"content\": \"recentPosts.0.content\",\n        \"likes\": 2\n      },\n      {\n        \"id\": \"recentPosts.1.id\",\n        \"content\": \"recentPosts.1.content\",\n        \"likes\": 2\n      }\n    ]\n  }\n}\n```\n\nTo understand how these values are derived, see [Default values](#default-values).\n\n## Mocking react-apollo\n\nIn addition to schema mocking, `\u003cMockApolloProvider\u003e` makes the testing of your UI components much easier.\n\nWrapping components in a `\u003cMockApolloProvider\u003e` allows any `graphql()` and `\u003cQuery\u003e` components in the tree to receive mock data.\nHowever note that components will first enter a loading state before the query resolves and components re-render.\n`\u003cMockApolloProvider\u003e`, together with a `controller`, allows you to step through GraphQL execution to test both loading and ready states.\n\n```javascript\nimport { MockApolloProvider, controller } from \"graphql-automock\";\nimport TestUtils from \"react-dom/test-utils\";\n\nit(\"renders a Post\", async () =\u003e {\n  const tree = TestUtils.renderIntoDocument(\n    \u003cMockApolloProvider schema={types}\u003e\n      \u003cPost id=\"123\" /\u003e\n    \u003c/MockApolloProvider\u003e\n  );\n\n  // Execution is automatically paused, allowing you to test loading state\n  const spinners = TestUtils.scryRenderedComponentsWithType(tree, Spinner);\n  expect(spinners).toHaveLength(1);\n\n  // Allow schema to run, and wait for it to finish\n  await controller.run();\n\n  // Test success state\n  const content = TestUtils.scryRenderedComponentsWithType(tree, Content);\n  expect(content).toHaveLength(1);\n});\n```\n\n## Customizing mocks\n\nAutomatically mocking the entire schema with sensible, deterministic data allows test code to customize _only the data that affects the test_. This results in test code that is more concise and easier to understand:\n\n```javascript\n// We're only interested in the behaviour of likes...\nit(\"hides the likes count when there are no likes\", () =\u003e {\n  const mocks = {\n    Post: () =\u003e ({\n      likes: 0 // ...so we only customize that data\n    })\n  };\n\n  // Using mockSchema\n  const mockedSchema = mockSchema({\n    schema: types,\n    mocks: mocks\n  });\n\n  // Using MockApolloProvider\n  const mockedElements = (\n    \u003cMockApolloProvider schema={types} mocks={mocks}\u003e\n      \u003cPost id=\"123\" /\u003e\n    \u003c/MockApolloProvider\u003e\n  );\n\n  // Continue with test...\n});\n```\n\n## Mocking errors\n\nBoth GraphQL errors and network errors can be mocked.\n\n### Mocking GraphQL errors\n\nJust like with a real GraphQL implementation, GraphQL errors are generated by throwing an error from a (mock) resolver.\n\n```javascript\nimport { mockSchema } from \"graphql-automock\";\n\nmockSchema({\n  schema: types,\n  mocks: {\n    Post: () =\u003e {\n      throw new Error(\"Could not retrieve Post\");\n    }\n  }\n});\n```\n\n### Mocking network errors\n\nSince network errors are external to the GraphQL schema, they are simulated through the `controller`.\n\n```javascript\nimport { MockApolloProvider, controller } from \"graphql-automock\";\nimport TestUtils from \"react-dom/test-utils\";\n\nit(\"renders a Post\", async () =\u003e {\n  const tree = TestUtils.renderIntoDocument(\n    \u003cMockApolloProvider schema={types}\u003e\n      \u003cPost id=\"123\" /\u003e\n    \u003c/MockApolloProvider\u003e\n  );\n\n  // Test loading state\n  const spinners = TestUtils.scryRenderedComponentsWithType(tree, Spinner);\n  expect(spinners).toHaveLength(1);\n\n  // Simulate a network error\n  await controller.run({\n    networkError: () =\u003e new Error(\"Disconnected\")\n  });\n\n  // Test error state\n  const errorMessage = TestUtils.scryRenderedComponentsWithType(\n    tree,\n    ErrorMessage\n  );\n  expect(errorMessage).toHaveLength(1);\n});\n```\n\n## Default values\n\nTo ensure that tests are reliable, the values generated by graphql-automock\nare 100% deterministic. The following default values are used:\n\n- **Boolean**: `true`\n- **Int**: `2`\n- **Float**: `3.14`\n- **String**: Path to value\n- **ID**: Path to value\n- **Enum**: The first enum value, sorted alphabetically by name\n- **Interface**: The first possible implementation, sorted alphabetically by name\n- **Union**: The first possible member type, sorted alphabetically by name\n- **List length**: `2`\n\n## API Reference\n\n### mockSchema()\n\nCreate a mocked GraphQL schema.\n\n```javascript\nfunction mockSchema(schema: String | GraphQLSchema): GraphQLSchema;\n\nfunction mockSchema({\n  schema: String | GraphQLSchema,\n  mocks: { [String]: MockResolverFn }\n}): GraphQLSchema;\n```\n\n### mockApolloClient()\n\nCreate a mocked Apollo Client.\n\n```javascript\nfunction mockApolloClient(schema: String | GraphQLSchema): ApolloClient;\n\nfunction mockApolloClient({\n  schema: String | GraphQLSchema,\n  mocks: { [String]: MockResolverFn },\n  controller: Controller\n}): ApolloClient;\n```\n\n### \\\u003cMockApolloProvider\\\u003e\n\nReact component that renders a mocked ApolloProvider.\n\n```javascript\n\u003cMockApolloProvider\n  schema={String | GraphQLSchema}\n  mocks={{ [String]: MockResolverFn }}\n  controller={Controller}\n\u003e\n```\n\n### type MockResolverFn\n\n```javascript\ntype MockResolverFn = (parent, args, context, info) =\u003e any;\n```\n\n### controller\n\nGives precise control over GraphQL execution, as well as enabling network errors to be simulated.\n\n#### pause()\n\n```javascript\nfunction pause(): void;\n```\n\nPause GraphQL execution until it is explicitly resumed.\n\n_Controller starts in this state._\n\n#### run()\n\n```javascript\nfunction run(): Promise\u003cvoid\u003e;\nfunction run({ networkError: () =\u003e any }): Promise\u003cvoid\u003e;\n```\n\nResume GraphQL execution if it is paused.\n\nReturns a Promise that resolves when all pending queries have finished executing. If execution was not paused, then it returns a resolved Promise.\n\nIf a `networkError` function is provided, pending and subsequent queries will fail with the result of calling that function. The function is called once for each query.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdvtng%2Fgraphql-automock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdvtng%2Fgraphql-automock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdvtng%2Fgraphql-automock/lists"}