Skip to content

Instantly share code, notes, and snippets.

@fernandes
Last active December 25, 2018 17:23
Show Gist options
  • Save fernandes/9b08ffd7ef10d8e181dc8bdb71e86c2a to your computer and use it in GitHub Desktop.
Save fernandes/9b08ffd7ef10d8e181dc8bdb71e86c2a to your computer and use it in GitHub Desktop.
Apollo Server 2 + Prisma, E2E Testing with AVA, with a technique to reset database and load some fixtures
const { ApolloServer, gql } = require('apollo-server')
const { Prisma } = require('../generated/prisma-client')
const { importSchema } = require('graphql-import')
const resolvers = require('./resolvers')
const importedTypeDefs = importSchema(__dirname + '/../generated/prisma.graphql');
const typeDefs = gql`${importedTypeDefs}`
const endpoint = 'http://localhost:4466'
const server = new ApolloServer({
typeDefs,
resolvers,
context: req => ({
...req,
db: new Prisma({
endpoint: endpoint,
}),
}),
resolverValidationOptions :{
requireResolversForResolveType: false
},
})
module.exports = server
import test from "ava"
const { createTestClient } = require('apollo-server-testing')
const { gql } = require('apollo-server')
const server = require('./server')
const { query, mutate } = createTestClient(server)
const GET_USERS = gql`
query getUsers {
users {
name
id
}
}
`
const CREATE_USER = gql`
mutation createUser($data : UserCreateInput!) {
createUser(data: $data) {
name
}
}
`
const loadFixtures = async () => {
await mutate({
mutation: CREATE_USER,
variables: { data: { name: "Fixture User" } }
})
}
test.beforeEach(async t => {
await fetch("http://localhost:4466/private", {
body: JSON.stringify({ query: "mutation { resetData }" }),
headers: { "content-type": "application/json" },
method: "post",
});
await loadFixtures()
});
test.serial("fixtures are loaded", async t => {
const res = await query({
query: GET_USERS
});
t.is(res.data.users.length, 1)
// check the names
const userNames = res.data.users.map((x) => x.name).sort()
t.deepEqual(userNames, ["Fixture User"])
});
test.serial("should list only user 1", async t => {
await mutate({
mutation: CREATE_USER,
variables: { data: { name: "Dummy 1" } }
})
const res = await query({
query: GET_USERS
});
t.is(res.data.users.length, 2)
// check the names
const userNames = res.data.users.map((x) => x.name).sort()
t.deepEqual(userNames, ["Dummy 1", "Fixture User"])
});
test.serial("should list only user 2", async t => {
await mutate({
mutation: CREATE_USER,
variables: { data: { name: "Dummy 2" } }
})
const res = await query({
query: GET_USERS
});
t.is(res.data.users.length, 2)
// check the names
const userNames = res.data.users.map((x) => x.name).sort()
t.deepEqual(userNames, ["Dummy 2", "Fixture User"])
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment