0.0.4 • Published 4 years ago

graphql-snapshot-testing v0.0.4

Weekly downloads
6
License
MIT
Repository
github
Last release
4 years ago

GraphQL Snapshot Testing

npm version

An interactive tool for writing snapshot test cases for GraphQL based requests.

  • Create basic interactive script for testing
  • Publish package on Yarn / NPM
  • Update code to allow non-interactive flag, and store diffs

Installation

# Yarn
yarn add graphql-snapshot-testing

# NPM
npm install graphql-snapshot-testing

How to use

// main.js
const ApolloClient = require("apollo-client").ApolloClient;
const fetch = require("node-fetch");
const createHttpLink = require("apollo-link-http").createHttpLink;
const InMemoryCache = require("apollo-cache-inmemory").InMemoryCache;
const gql = require("graphql-tag");
const gst = require("graphql-snapshot-testing");

const client = new ApolloClient({
  link: createHttpLink({
    uri: args.url,
    fetch: fetch
  }),
  cache: new InMemoryCache()
});

const USERS = gql`
  query Users($first: Int) {
    users(first: $first) {
      edges {
        node {
          id
          username
        }
      }
    }
  }
`

async function runTests() {
  // Run the snapshots in order
  await gst.snapshotTest(client, "users/snapshots", "Get the first 2 users", USERS, {"first": 2});
}

runTests();

Now, if this is the first time running this query, the second argument (users/snapshots in the above example), graphql-snapshot-testing will automatically create that directory for you, and inside that directory will create a file called Get the first 2 users.json, and the following will get printed to the console:

<<<<<<< New cache for "Get the first 2 users" >>>>>>>

The next time this test is ran, if the result is the same as what is in the snapshot, we will see:

✓ Passed (Get the first 2 users)

And if the result is different, we will see the following:

✗ Failed (Get the first 2 users)
? What do you want to do?
❯ Show diff and exit
  Show diff and continue
  Exit

If you choose to see the diff, you will something like:

{
    "pages": {
        "edges": [
            {
                "node": {
                    "username": "user-1"
                    "__typename": "User"
                },
                "__typename": "UserEdge"
            },
            {
                "node": {
-                    "username": "user-2"
+                    "username": null
                    "__typename": "User"
                },
                "__typename": "UserEdge"
            },
        ],
        "__typename": "UserConnection"
    }
}