├── CHANGELOG.md ├── .npmignore ├── .prettierignore ├── .eslintignore ├── .gitignore ├── prettier.config.js ├── assets └── logo.png ├── .huskyrc.js ├── lint-staged.config.js ├── tsconfig.eslint.json ├── src ├── index.ts ├── merge-resolvers.ts ├── types.ts ├── mock-factory.test.ts └── mock-factory.ts ├── babel.config.js ├── .eslintrc.js ├── tsconfig.json ├── LICENSE ├── package.json ├── .circleci └── config.yml ├── README.md └── jest.config.ts /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | *.test.* -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | coverage/ 2 | lib/ -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | lib/ 3 | coverage/ -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | lib/ 3 | coverage/ 4 | yarn-error.log 5 | .env -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | module.exports = require("@ravn-dev/prettier-config") 2 | -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ravnhq/mimicql/HEAD/assets/logo.png -------------------------------------------------------------------------------- /.huskyrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | hooks: { 3 | "pre-commit": "lint-staged", 4 | }, 5 | } 6 | -------------------------------------------------------------------------------- /lint-staged.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "*.{ts,tsx,js,jsx,json,md}": ["prettier --write"], 3 | } 4 | -------------------------------------------------------------------------------- /tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": [".*.*", "*.*.*", "src/**/*"] 4 | } 5 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import MockFactory from "./mock-factory" 2 | 3 | export * from "./types" 4 | export { MockList } from "graphql-tools" 5 | export default MockFactory 6 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | ["@babel/preset-env", { targets: { node: "current" } }], 4 | "@babel/preset-typescript", 5 | ], 6 | } 7 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parserOptions: { 4 | project: "./tsconfig.eslint.json", 5 | }, 6 | extends: [ 7 | "@ravn-dev/eslint-config-ravn/base", 8 | "@ravn-dev/eslint-config-ravn/jest", 9 | "@ravn-dev/eslint-config-ravn/typescript", 10 | ], 11 | rules: {}, 12 | overrides: [ 13 | { 14 | files: ["**/*.test.{ts,tsx}"], 15 | rules: { 16 | "@typescript-eslint/no-unsafe-assignment": "off", 17 | "@typescript-eslint/no-unsafe-member-access": "off", 18 | }, 19 | }, 20 | ], 21 | } 22 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "lib", 4 | "target": "es5", 5 | "module": "commonjs", 6 | "moduleResolution": "node", 7 | "lib": ["esnext"], 8 | "allowSyntheticDefaultImports": true, 9 | "esModuleInterop": true, 10 | "importHelpers": true, 11 | "resolveJsonModule": true, 12 | "sourceMap": true, 13 | "declaration": true, 14 | "noFallthroughCasesInSwitch": true, 15 | "noImplicitUseStrict": false, 16 | "noImplicitAny": false, 17 | "noStrictGenericChecks": false, 18 | "noUnusedParameters": true, 19 | "strict": true, 20 | "skipLibCheck": true 21 | }, 22 | "include": ["src"] 23 | } 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Donovan Hiland 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/merge-resolvers.ts: -------------------------------------------------------------------------------- 1 | import { ResolverMap } from "./types" 2 | 3 | const mergeResolvers = (target: ResolverMap, input: ResolverMap) => { 4 | const inputTypenames = Object.keys(input) 5 | const merged: ResolverMap = inputTypenames.reduce( 6 | (accum, key) => { 7 | const inputResolver = input[key] 8 | if (target.hasOwnProperty(key)) { 9 | const targetResolver = target[key] 10 | const resolvedInput = inputResolver() 11 | const resolvedTarget = targetResolver() 12 | if ( 13 | !!resolvedTarget && 14 | !!resolvedInput && 15 | typeof resolvedTarget === "object" && 16 | typeof resolvedInput === "object" && 17 | !Array.isArray(resolvedTarget) && 18 | !Array.isArray(resolvedInput) 19 | ) { 20 | const newValue = { ...resolvedTarget, ...resolvedInput } 21 | 22 | return { 23 | ...accum, 24 | [key]: () => newValue, 25 | } 26 | } 27 | } 28 | return { ...accum, [key]: inputResolver } 29 | }, 30 | { ...target }, 31 | ) 32 | return merged 33 | } 34 | 35 | export default mergeResolvers 36 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import { GraphQLResolveInfo } from "graphql" 2 | 3 | type ResolvedScalar = string | number | boolean | null 4 | type ResolvedValue = 5 | | ResolvedScalar 6 | | Array 7 | | { [key: string]: ResolvedValue } 8 | export type ResolverFunction = (...args: any[]) => ResolvedValue 9 | 10 | type NonRecord = string | boolean | number | null | undefined | Date 11 | 12 | type ScalarPropertyKeys = { 13 | [P in keyof T]: Exclude extends never ? P : never 14 | }[keyof T] 15 | 16 | type WithoutTypename = Exclude 17 | 18 | export type ShallowProperties = { 19 | [K in WithoutTypename>]: Exclude 20 | } 21 | 22 | export type MockResolvedValue = { 23 | [K in keyof T]: T[K] | ((root: any, args: any) => MockResolvedValue) 24 | } 25 | 26 | export type ShallowResolvedValue = MockResolvedValue> 27 | 28 | export type MockResolver< 29 | TData, 30 | TSource = any, 31 | TContext = any, 32 | TArgs = { [argName: string]: any } 33 | > = ( 34 | source?: TSource, 35 | args?: TArgs, 36 | context?: TContext, 37 | info?: GraphQLResolveInfo, 38 | ) => MockResolvedValue | ResolvedScalar | ResolverMap 39 | 40 | export type ResolverMap = { 41 | [key: string]: MockResolver 42 | } 43 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mimicql", 3 | "version": "0.0.0-development", 4 | "description": "Mimic your graphql API by quickly and easily generating mock graphql data in the browser and node.js", 5 | "repository": "https://github.com/ravnhq/mimicql", 6 | "author": "https://www.ravn.co/", 7 | "bugs": { 8 | "url": "https://www.github.com/ravnhq/mimicql/issues" 9 | }, 10 | "homepage": "https://www.github.com/ravnhq/mimicql#readme", 11 | "license": "MIT", 12 | "publishConfig": { 13 | "registry": "https://registry.npmjs.org/" 14 | }, 15 | "main": "dist/index.js", 16 | "types": "dist/index.d.ts", 17 | "files": [ 18 | "src", 19 | "dist" 20 | ], 21 | "scripts": { 22 | "build": "tsc", 23 | "watch-build": "npx tsc-watch", 24 | "format:write": "yarn format --list-different --write", 25 | "static": "npm-run-all --parallel -c tsc lint format:check", 26 | "test": "jest", 27 | "typescript": "tsc --noEmit", 28 | "lint": "eslint \"**/*.{js,ts,tsx}\"", 29 | "format": "prettier .", 30 | "format:check": "yarn format --check", 31 | "validate": "npm-run-all typescript lint format:check", 32 | "prepublishOnly": "yarn build", 33 | "release": "yarn semantic-release", 34 | "semantic-release": "semantic-release" 35 | }, 36 | "keywords": [ 37 | "graphql", 38 | "mock", 39 | "test", 40 | "mock data generator", 41 | "msw", 42 | "apollo", 43 | "relay" 44 | ], 45 | "dependencies": { 46 | "apollo-utilities": "^1.3.4", 47 | "graphql-tools": "^4.0.8" 48 | }, 49 | "devDependencies": { 50 | "@babel/core": "^7.12.10", 51 | "@babel/preset-env": "^7.12.10", 52 | "@babel/preset-typescript": "^7.12.7", 53 | "@ravn-dev/eslint-config-ravn": "^4.0.1", 54 | "@ravn-dev/prettier-config": "^1.0.0", 55 | "@types/jest": "^26.0.19", 56 | "babel-jest": "^26.6.3", 57 | "eslint": "^7.15.0", 58 | "graphql": "^15.4.0", 59 | "graphql-tag": "^2.11.0", 60 | "husky": "^4.2.5", 61 | "jest": "^26.6.3", 62 | "lint-staged": "^10.2.11", 63 | "npm-run-all": "^4.1.5", 64 | "prettier": "^2.0.5", 65 | "semantic-release": "^17.4.3", 66 | "ts-node": "^9.1.1", 67 | "typescript": "^3.9.7" 68 | }, 69 | "peerDependencies": { 70 | "graphql": "^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0" 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | references: 4 | ignore_master: &ignore_master 5 | filters: 6 | branches: 7 | ignore: 8 | - master 9 | 10 | only_master: &only_master 11 | filters: 12 | branches: 13 | only: 14 | - master 15 | 16 | yarn_key: &yarn_key yarn-nm-cache-v1-{{ checksum "yarn.lock" }}-{{ checksum "package.json" }}-{{ arch }} 17 | 18 | restore_yarn_cache: &restore_yarn_cache 19 | restore_cache: 20 | keys: 21 | - *yarn_key 22 | 23 | save_yarn_cache: &save_yarn_cache 24 | save_cache: 25 | name: Saving Cache - yarn 26 | key: *yarn_key 27 | paths: 28 | - ~/.cache/yarn 29 | - node_modules 30 | 31 | install_javascript_dependencies: &install_javascript_dependencies 32 | run: 33 | name: Download javascript dependencies (node_modules) 34 | command: yarn install --frozen-lockfile 35 | 36 | jobs: 37 | validate: 38 | docker: 39 | - image: circleci/node:14 40 | 41 | steps: 42 | - checkout 43 | - *restore_yarn_cache 44 | - *install_javascript_dependencies 45 | - *save_yarn_cache 46 | - run: 47 | name: Typescript 48 | command: yarn typescript 49 | - run: 50 | name: Lint 51 | command: yarn lint 52 | - run: 53 | name: Formatting 54 | command: yarn format:check 55 | - run: 56 | name: Test 57 | command: yarn test --coverage 58 | - run: 59 | name: Upload coverage 60 | command: >- 61 | bash <(curl -s https://codecov.io/bash) \ 62 | -n ${CIRCLE_BUILD_NUM} \ 63 | -t ${CODECOV_TOKEN} \ 64 | -F \ 65 | 66 | release: 67 | docker: 68 | - image: circleci/node:14 69 | 70 | steps: 71 | - checkout 72 | # We duplicate installing dependencies rather than using the deps from previous steps. Maybe change this. 73 | - *restore_yarn_cache 74 | - *install_javascript_dependencies 75 | - *save_yarn_cache 76 | - run: npx semantic-release 77 | 78 | workflows: 79 | validate_pr: 80 | jobs: 81 | - validate: 82 | <<: *ignore_master 83 | 84 | validate_and_release: 85 | jobs: 86 | - validate: 87 | <<: *only_master 88 | - release: 89 | <<: *only_master 90 | requires: 91 | - validate 92 | -------------------------------------------------------------------------------- /src/mock-factory.test.ts: -------------------------------------------------------------------------------- 1 | import { buildASTSchema, introspectionFromSchema } from "graphql" 2 | import gql from "graphql-tag" 3 | import MockFactory from "./mock-factory" 4 | 5 | const schema = gql` 6 | type Rocket { 7 | id: ID! 8 | name: String 9 | type: String 10 | } 11 | 12 | type Launch { 13 | id: ID! 14 | site: String 15 | mission: Mission 16 | rocket: Rocket 17 | isBooked: Boolean! 18 | } 19 | 20 | type TripsEdge { 21 | node: Launch 22 | } 23 | 24 | type TripsConnection { 25 | edges: [TripsEdge] 26 | } 27 | 28 | type User { 29 | id: ID! 30 | email: String! 31 | trips: [Launch]! 32 | tripsConnection: TripsConnection 33 | } 34 | 35 | enum PatchSize { 36 | SMALL 37 | LARGE 38 | } 39 | 40 | type Mission { 41 | name: String 42 | missionPatch(size: PatchSize!): String 43 | } 44 | 45 | type TripUpdateResponse { 46 | success: Boolean! 47 | message: String 48 | launches: [Launch] 49 | } 50 | 51 | type Query { 52 | rockets: [Rocket]! 53 | launches: [Launch]! 54 | launch(id: ID!): Launch 55 | me: User 56 | } 57 | 58 | type Mutation { 59 | bookTrips(launchIds: [ID]!): TripUpdateResponse! 60 | cancelTrip(launchId: ID!): TripUpdateResponse! 61 | login(email: String): String 62 | } 63 | ` 64 | 65 | const jsonSchema = introspectionFromSchema(buildASTSchema(schema)) 66 | 67 | test("can mock a fragment that contains variables", () => { 68 | const mocker = new MockFactory(jsonSchema) 69 | const mockMap = { 70 | Mission: () => ({ 71 | missionPatch: (_, missionPatchArgs) => { 72 | return missionPatchArgs.size 73 | }, 74 | }), 75 | } 76 | const fragmentWithVariables = gql` 77 | query($patchSize: String!) { 78 | mock__Mission { 79 | ...MissionPatch 80 | } 81 | } 82 | 83 | fragment MissionPatch on Mission { 84 | missionPatch(size: $patchSize) 85 | } 86 | ` 87 | 88 | const variables = { patchSize: "SMALL" } 89 | const mockMissionPatch = mocker.mockQuery(fragmentWithVariables, { 90 | mocks: mockMap, 91 | variables, 92 | addTypename: false, 93 | }) 94 | 95 | expect(mockMissionPatch).toMatchInlineSnapshot(` 96 | Object { 97 | "mock__Mission": Object { 98 | "missionPatch": "SMALL", 99 | }, 100 | } 101 | `) 102 | }) 103 | 104 | describe("addTypename", () => { 105 | const fragment = gql` 106 | fragment Rocket on Rocket { 107 | name 108 | } 109 | ` 110 | const query = gql` 111 | query Me { 112 | me { 113 | id 114 | } 115 | } 116 | ` 117 | const mutation = gql` 118 | mutation BookTrips { 119 | bookTrips(launchIds: ["1"]) { 120 | success 121 | } 122 | } 123 | ` 124 | 125 | const mockedFragmentTypename = (mocker: MockFactory) => 126 | mocker.mockFragment(fragment).__typename 127 | 128 | const mockedQueryTypename = (mocker: MockFactory) => 129 | mocker.mockQuery(query).me.__typename 130 | 131 | const mockedMutationTypename = (mocker: MockFactory) => 132 | mocker.mockMutation(mutation).bookTrips.__typename 133 | 134 | const mockedDataTypenames = (mocker: MockFactory) => { 135 | return { 136 | fragmentTypename: mockedFragmentTypename(mocker), 137 | queryTypename: mockedQueryTypename(mocker), 138 | mutationTypename: mockedMutationTypename(mocker), 139 | } 140 | } 141 | 142 | test("globally defaults to true", () => { 143 | const defaultMocker = new MockFactory(jsonSchema) 144 | 145 | const { 146 | fragmentTypename, 147 | queryTypename, 148 | mutationTypename, 149 | } = mockedDataTypenames(defaultMocker) 150 | 151 | expect(fragmentTypename).toBe("Rocket") 152 | expect(queryTypename).toBe("User") 153 | expect(mutationTypename).toBe("TripUpdateResponse") 154 | }) 155 | 156 | test("globally override to true", () => { 157 | const mockerWithTypenameExplicit = new MockFactory(jsonSchema, { 158 | addTypename: true, 159 | }) 160 | 161 | const { 162 | fragmentTypename, 163 | queryTypename, 164 | mutationTypename, 165 | } = mockedDataTypenames(mockerWithTypenameExplicit) 166 | 167 | expect(fragmentTypename).toBe("Rocket") 168 | expect(queryTypename).toBe("User") 169 | expect(mutationTypename).toBe("TripUpdateResponse") 170 | }) 171 | 172 | test("globally override to false", () => { 173 | const mockerWithoutTypenameExplicit = new MockFactory(jsonSchema, { 174 | addTypename: false, 175 | }) 176 | 177 | const { 178 | fragmentTypename, 179 | queryTypename, 180 | mutationTypename, 181 | } = mockedDataTypenames(mockerWithoutTypenameExplicit) 182 | 183 | expect(fragmentTypename).toBeUndefined() 184 | expect(queryTypename).toBeUndefined() 185 | expect(mutationTypename).toBeUndefined() 186 | }) 187 | }) 188 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 |

MimicQL

6 | 7 |
8 | 9 | Mimic your graphql API by quickly and easily generating mock graphql data in the 10 | browser and node.js 11 | 12 | [![CI status][circle-ci-image]][circle-ci-url] [![codecov][codecov-image]][codecov-url] ![semantic-release][semantic-release-image] [![NPM version][npm-image]][npm-url] [![NPM downloads][download-image]][download-url] 13 | 14 | [circle-ci-image]: https://circleci.com/gh/ravnhq/mimicql.svg?style=shield 15 | [circle-ci-url]: https://github.com/ravnhq/mimicql/actions/workflows/validate.yml?query=branch%3Amaster 16 | [codecov-image]: https://img.shields.io/codecov/c/github/ravnhq/mimicql/master.svg?style=flat 17 | [codecov-url]: https://codecov.io/gh/ravnhq/mimicql/branch/master 18 | [semantic-release-image]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg 19 | [npm-image]: https://img.shields.io/npm/v/mimicql?style=flat 20 | [npm-url]: http://npmjs.org/package/mimicql 21 | [download-image]: https://img.shields.io/npm/dw/mimicql?style=flat 22 | [download-url]: https://npmjs.org/package/mimicql 23 | 24 |
25 | 26 | ## The problem 27 | 28 | You want to write maintainable tests in a codebase that interacts with a graphql 29 | API and you need mock data. You need mocked data to match the structure of your 30 | document which can be a pain given the dynamic and nested nature of graphql 31 | queries. You want to have sensible data generated for you by default and the 32 | ability to customize on a case by case basis. 33 | 34 | ## The solution 35 | 36 | `MimicQL` is a small but robust solution for generating mocked graphql data. It 37 | provides functions for generating mock data that will match your query, 38 | mutation, and fragment definition structures. It gives you the ability to define 39 | the way your graphql schema should resolve and execute queries, mutations, AND 40 | fragments against it. 41 | 42 | ## Getting Started 43 | 44 | ### Installation 45 | 46 | This module is distributed via [npm][npm] which is bundled with [node][node] and 47 | should be installed as one of your project's `devDependencies`: 48 | 49 | ``` 50 | npm install --save-dev mimicQL 51 | ``` 52 | 53 | or 54 | 55 | for installation via [yarn][yarn] 56 | 57 | ``` 58 | yarn add --dev mimicQL 59 | ``` 60 | 61 | ### Create Mocker 62 | 63 | First create a file where your mocker instance will live. To initialize your 64 | mocker you need to pass a JSON schema into the mock factory generator exposed 65 | from mimicQL. 66 | 67 | ```js 68 | // mocker.js 69 | import MockFactory from "mimicQL" 70 | import schemaJson from "path/to/schema.json" 71 | 72 | export default new MockFactory(schemaJson) 73 | ``` 74 | 75 | At this point you can generate mock data but without supplying default mock 76 | resolvers but your data will consist of only default values for each type. You 77 | will more than likely want to have some sensible defaults. 78 | 79 | ### Create Default Mock Resolvers 80 | 81 | To do that we'll want to define mock resolvers. The documentation on what 82 | constitutes a mock resolver can be found 83 | [here](https://www.graphql-tools.com/docs/resolvers). 84 | 85 | ```js 86 | // resolvers/Rocket.js 87 | import faker from "faker" 88 | 89 | const MockRocket = () => { 90 | return { 91 | id: () => `rocket-${faker.random.uuid()}`, 92 | name: () => `rocket-${faker.random.word()}`, 93 | type: () => `rocket-${faker.random.word()}`, 94 | } 95 | } 96 | 97 | export default MockRocket 98 | ``` 99 | 100 | Generally you only want to define values for the shallow properties on an 101 | object. You'll leave value definition for nested types to the resolver in charge 102 | of that type. For example if a `Launch` has a `rocket: Rocket` field you should 103 | leave the definition for `rocket` to the `Rocket` resolver. 104 | 105 | ### Setup Mock Server 106 | 107 | Head back to the mocker and add the new mock `Rocket` resolver so it can use it 108 | for its defaults. 109 | 110 | ```js 111 | // mocker.js 112 | import MockFactory from 'mimicQL' 113 | import schemaJson from 'path/to/schema.json' 114 | import Rocket from './resolvers/Rocket' 115 | 116 | export default new MockFactory( 117 | schemaJson, 118 | { mocks: { Rocket } 119 | ) 120 | ``` 121 | 122 | ### Execute Query 123 | 124 | Now with a valid graphql document we can generate some sensible mock data. 125 | 126 | ```ts 127 | import gql from "graphql-tag" 128 | import mocker from "./mocker" 129 | 130 | const query = gql` 131 | query Rockets($id: ID!) { 132 | rockets { 133 | id 134 | name 135 | type 136 | } 137 | } 138 | ` 139 | 140 | const mockedRocketsQuery = mocker.mockQuery(query) 141 | /** 142 | * [ 143 | * { 144 | * id: 'rocket-', 145 | * name: 'rocket-', 146 | * type: 'rocket-', 147 | * __typename: 'Rocket' 148 | * }, 149 | * { 150 | * id: 'rocket-', 151 | * name: 'rocket-', 152 | * type: 'rocket-', 153 | * __typename: 'Rocket' 154 | * }, 155 | * ] 156 | */ 157 | ``` 158 | 159 | ### Using variables 160 | 161 | ## Recipes & Examples 162 | 163 | TODO 164 | 165 | [npm]: https://www.npmjs.com/ 166 | [yarn]: https://classic.yarnpkg.com 167 | [node]: https://nodejs.org 168 | -------------------------------------------------------------------------------- /jest.config.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * For a detailed explanation regarding each configuration property and type check, visit: 3 | * https://jestjs.io/docs/en/configuration.html 4 | */ 5 | 6 | export default { 7 | // All imported modules in your tests should be mocked automatically 8 | // automock: false, 9 | 10 | // Stop running tests after `n` failures 11 | // bail: 0, 12 | 13 | // The directory where Jest should store its cached dependency information 14 | // cacheDirectory: "/private/var/folders/nv/yh4bj9sj0d72mz4x6sfnfw640000gn/T/jest_dx", 15 | 16 | // Automatically clear mock calls and instances between every test 17 | clearMocks: true, 18 | 19 | // Indicates whether the coverage information should be collected while executing the test 20 | // collectCoverage: false, 21 | 22 | // An array of glob patterns indicating a set of files for which coverage information should be collected 23 | collectCoverageFrom: ["./src/**/*.{ts,tsx}"], 24 | 25 | // The directory where Jest should output its coverage files 26 | coverageDirectory: "coverage", 27 | 28 | // An array of regexp pattern strings used to skip coverage collection 29 | // coveragePathIgnorePatterns: [ 30 | // "/node_modules/" 31 | // ], 32 | 33 | // Indicates which provider should be used to instrument code for coverage 34 | coverageProvider: "v8", 35 | 36 | // A list of reporter names that Jest uses when writing coverage reports 37 | // coverageReporters: [ 38 | // "json", 39 | // "text", 40 | // "lcov", 41 | // "clover" 42 | // ], 43 | 44 | // An object that configures minimum threshold enforcement for coverage results 45 | // coverageThreshold: undefined, 46 | 47 | // A path to a custom dependency extractor 48 | // dependencyExtractor: undefined, 49 | 50 | // Make calling deprecated APIs throw helpful error messages 51 | // errorOnDeprecated: false, 52 | 53 | // Force coverage collection from ignored files using an array of glob patterns 54 | // forceCoverageMatch: [], 55 | 56 | // A path to a module which exports an async function that is triggered once before all test suites 57 | // globalSetup: undefined, 58 | 59 | // A path to a module which exports an async function that is triggered once after all test suites 60 | // globalTeardown: undefined, 61 | 62 | // A set of global variables that need to be available in all test environments 63 | // globals: {}, 64 | 65 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 66 | // maxWorkers: "50%", 67 | 68 | // An array of directory names to be searched recursively up from the requiring module's location 69 | moduleDirectories: ["node_modules", ""], 70 | 71 | // An array of file extensions your modules use 72 | // moduleFileExtensions: [ 73 | // "js", 74 | // "json", 75 | // "jsx", 76 | // "ts", 77 | // "tsx", 78 | // "node" 79 | // ], 80 | 81 | // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module 82 | // moduleNameMapper: {}, 83 | 84 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 85 | modulePathIgnorePatterns: ["lib"], 86 | 87 | // Activates notifications for test results 88 | // notify: false, 89 | 90 | // An enum that specifies notification mode. Requires { notify: true } 91 | // notifyMode: "failure-change", 92 | 93 | // A preset that is used as a base for Jest's configuration 94 | // preset: undefined, 95 | 96 | // Run tests from one or more projects 97 | // projects: undefined, 98 | 99 | // Use this configuration option to add custom reporters to Jest 100 | // reporters: undefined, 101 | 102 | // Automatically reset mock state between every test 103 | // resetMocks: false, 104 | 105 | // Reset the module registry before running each individual test 106 | // resetModules: false, 107 | 108 | // A path to a custom resolver 109 | // resolver: undefined, 110 | 111 | // Automatically restore mock state between every test 112 | // restoreMocks: false, 113 | 114 | // The root directory that Jest should scan for tests and modules within 115 | // rootDir: undefined, 116 | 117 | // A list of paths to directories that Jest should use to search for files in 118 | // roots: [ 119 | // "" 120 | // ], 121 | 122 | // Allows you to use a custom runner instead of Jest's default test runner 123 | // runner: "jest-runner", 124 | 125 | // The paths to modules that run some code to configure or set up the testing environment before each test 126 | // setupFiles: [], 127 | 128 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 129 | // setupFilesAfterEnv: [], 130 | 131 | // The number of seconds after which a test is considered as slow and reported as such in the results. 132 | // slowTestThreshold: 5, 133 | 134 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 135 | // snapshotSerializers: [], 136 | 137 | // The test environment that will be used for testing 138 | testEnvironment: "node", 139 | 140 | // Options that will be passed to the testEnvironment 141 | // testEnvironmentOptions: {}, 142 | 143 | // Adds a location field to test results 144 | // testLocationInResults: false, 145 | 146 | // The glob patterns Jest uses to detect test files 147 | // testMatch: [ 148 | // "**/__tests__/**/*.[jt]s?(x)", 149 | // "**/?(*.)+(spec|test).[tj]s?(x)" 150 | // ], 151 | 152 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 153 | // testPathIgnorePatterns: [ 154 | // "/node_modules/" 155 | // ], 156 | 157 | // The regexp pattern or array of patterns that Jest uses to detect test files 158 | // testRegex: [], 159 | 160 | // This option allows the use of a custom results processor 161 | // testResultsProcessor: undefined, 162 | 163 | // This option allows use of a custom test runner 164 | // testRunner: "jasmine2", 165 | 166 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 167 | // testURL: "http://localhost", 168 | 169 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 170 | // timers: "real", 171 | 172 | // A map from regular expressions to paths to transformers 173 | // transform: undefined, 174 | 175 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 176 | // transformIgnorePatterns: [ 177 | // "/node_modules/", 178 | // "\\.pnp\\.[^\\/]+$" 179 | // ], 180 | 181 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 182 | // unmockedModulePathPatterns: undefined, 183 | 184 | // Indicates whether each individual test should be reported during the run 185 | // verbose: undefined, 186 | 187 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 188 | // watchPathIgnorePatterns: [], 189 | 190 | // Whether to use watchman for file crawling 191 | // watchman: true, 192 | } 193 | -------------------------------------------------------------------------------- /src/mock-factory.ts: -------------------------------------------------------------------------------- 1 | import { 2 | buildClientSchema, 3 | DocumentNode, 4 | GraphQLSchema, 5 | execute, 6 | GraphQLObjectType, 7 | GraphQLInterfaceType, 8 | print, 9 | IntrospectionQuery, 10 | parse, 11 | } from "graphql" 12 | import { getMainDefinition, addTypenameToDocument } from "apollo-utilities" 13 | import { 14 | addMockFunctionsToSchema, 15 | transformSchema, 16 | mergeSchemas, 17 | } from "graphql-tools" 18 | import { ResolverMap } from "./types" 19 | import mergeResolvers from "./merge-resolvers" 20 | 21 | const buildMockSchema = (schemaJson: IntrospectionQuery) => { 22 | const originalSchema = buildClientSchema(schemaJson) 23 | 24 | const typeMap = originalSchema.getTypeMap() 25 | const allTypeFields = Object.keys(typeMap).reduce((fields, typeName) => { 26 | const type = typeMap[typeName] 27 | if ( 28 | typeName.startsWith("__") || 29 | typeName === "Query" || 30 | typeName === "Mutation" || 31 | (!(type instanceof GraphQLObjectType) && 32 | !(type instanceof GraphQLInterfaceType)) 33 | ) { 34 | return fields 35 | } 36 | return { 37 | ...fields, 38 | [`mock__${typeName}`]: { type: typeMap[typeName] }, 39 | } 40 | }, {}) 41 | 42 | const mockSchema = new GraphQLSchema({ 43 | query: new GraphQLObjectType({ name: "Query", fields: allTypeFields }), 44 | }) 45 | 46 | return mergeSchemas({ schemas: [originalSchema, mockSchema] }) 47 | } 48 | 49 | const executeOperation = ( 50 | schema: GraphQLSchema, 51 | operationDocument: DocumentNode, 52 | variables?: { [key: string]: any }, 53 | ) => { 54 | const result = execute(schema, operationDocument, undefined, {}, variables) 55 | 56 | if (result instanceof Promise) { 57 | throw new Error("Async mock resolvers aren't supported yet") 58 | } 59 | if (result.errors?.length) { 60 | throw result.errors[0] 61 | } 62 | 63 | return result 64 | } 65 | 66 | interface Options { 67 | mocks?: ResolverMap 68 | addTypename?: boolean 69 | } 70 | 71 | interface MockOptions { 72 | variables?: TVariables 73 | mocks?: ResolverMap 74 | addTypename?: boolean 75 | } 76 | 77 | class MockFactory { 78 | private schema: GraphQLSchema 79 | private mocks: ResolverMap 80 | private addTypename: boolean 81 | 82 | private mockSchema(options: { mocks?: ResolverMap } = {}) { 83 | const clonedSchema = transformSchema(this.schema, []) 84 | const mergedMocks = mergeResolvers(this.mocks, options.mocks ?? {}) 85 | addMockFunctionsToSchema({ schema: clonedSchema, mocks: mergedMocks }) 86 | return clonedSchema 87 | } 88 | 89 | private maybeAddTypenameToDocument = ( 90 | document: DocumentNode, 91 | overrideAddTypename: boolean | undefined, 92 | ) => { 93 | const addTypename = overrideAddTypename ?? this.addTypename 94 | return addTypename ? addTypenameToDocument(document) : document 95 | } 96 | 97 | constructor( 98 | schema: IntrospectionQuery, 99 | { mocks, addTypename = true }: Options = {}, 100 | ) { 101 | this.schema = buildMockSchema(schema) 102 | this.mocks = mocks ?? {} 103 | this.addTypename = addTypename 104 | } 105 | 106 | mockFragment = ( 107 | fragment: DocumentNode, 108 | options: Pick< 109 | MockOptions>, 110 | "addTypename" | "mocks" 111 | > = {}, 112 | ): TData => { 113 | const { mocks = {}, addTypename } = options 114 | 115 | const fragmentDocument = this.maybeAddTypenameToDocument( 116 | fragment, 117 | addTypename, 118 | ) 119 | const mainDefinition = getMainDefinition(fragmentDocument) 120 | 121 | if (mainDefinition.kind !== "FragmentDefinition") { 122 | throw new Error( 123 | "MockFactory: mockFragment only accepts fragment documents", 124 | ) 125 | } 126 | 127 | const typeName = mainDefinition.typeCondition.name.value 128 | const fieldName = `mock__${typeName}` 129 | const query = parse(/* GraphQL */ ` 130 | query { 131 | ${fieldName} { 132 | ...${mainDefinition.name.value} 133 | } 134 | } 135 | ${print(fragmentDocument)} 136 | `) 137 | 138 | const mockedSchema = this.mockSchema({ mocks }) 139 | 140 | const result = executeOperation(mockedSchema, query) 141 | 142 | if (!result.data || result.data[fieldName] === undefined) { 143 | throw new Error( 144 | [ 145 | `Unable to generate mock data for ${ 146 | mainDefinition.name.value || "fragment" 147 | }. This could be a result of missing mock resolvers or an incorrect fragment structure.`, 148 | print(fragment), 149 | ].join("\n"), 150 | ) 151 | } 152 | 153 | return JSON.parse(JSON.stringify(result.data[fieldName])) as TData 154 | } 155 | 156 | mockQuery = ( 157 | query: DocumentNode, 158 | options: MockOptions = {}, 159 | ) => { 160 | const { variables = {}, mocks = {}, addTypename } = options 161 | 162 | const queryDocument = this.maybeAddTypenameToDocument(query, addTypename) 163 | const mainDefinition = getMainDefinition(queryDocument) 164 | 165 | if ( 166 | mainDefinition.kind !== "OperationDefinition" || 167 | mainDefinition.operation !== "query" 168 | ) { 169 | throw new Error("MockFactory: mockQuery only accepts query documents") 170 | } 171 | 172 | const mockedSchema = this.mockSchema({ mocks }) 173 | 174 | const result = executeOperation(mockedSchema, queryDocument, variables) 175 | 176 | if (!result.data) { 177 | throw new Error( 178 | [ 179 | `Unable to generate mock data for ${ 180 | mainDefinition.name?.value ?? "unnamed" 181 | } query. This could be a result of missing mock resolvers, incorrect query structure, or missing variables.`, 182 | `variables: ${JSON.stringify(variables, null, 2)}`, 183 | print(query), 184 | ].join("\n"), 185 | ) 186 | } 187 | 188 | return JSON.parse(JSON.stringify(result.data)) as TData 189 | } 190 | 191 | mockMutation = ( 192 | mutation: DocumentNode, 193 | options: MockOptions = {}, 194 | ) => { 195 | const { variables = {}, mocks = {}, addTypename } = options 196 | 197 | const mutationDocument = this.maybeAddTypenameToDocument( 198 | mutation, 199 | addTypename, 200 | ) 201 | const mainDefinition = getMainDefinition(mutationDocument) 202 | 203 | if ( 204 | mainDefinition.kind !== "OperationDefinition" || 205 | mainDefinition.operation !== "mutation" 206 | ) { 207 | throw new Error( 208 | "MockFactory: mockMutation only accepts mutation documents", 209 | ) 210 | } 211 | 212 | const mockedSchema = this.mockSchema({ mocks }) 213 | 214 | const result = executeOperation(mockedSchema, mutationDocument, variables) 215 | 216 | if (!result.data) { 217 | throw new Error( 218 | [ 219 | `Unable to generate mock data for ${ 220 | mainDefinition.name?.value ?? "unnamed" 221 | } mutation. This could be a result of missing mock resolvers, incorrect mutation structure, or missing variables.`, 222 | `variables: ${JSON.stringify(variables, null, 2)}`, 223 | print(mutation), 224 | ].join("\n"), 225 | ) 226 | } 227 | 228 | return JSON.parse(JSON.stringify(result.data)) as TData 229 | } 230 | } 231 | 232 | export default MockFactory 233 | --------------------------------------------------------------------------------