diff --git a/src/jest/helpers.js b/src/jest/helpers.js index f687305ea..28aed9f98 100644 --- a/src/jest/helpers.js +++ b/src/jest/helpers.js @@ -1,15 +1,27 @@ import { request } from 'graphql-request' +import { GraphQLClient } from 'graphql-request' export const host = 'http://127.0.0.1:3123' -export async function login ({ email, password }) { +export async function getJWT({ email, password }) { const mutation = ` mutation { login(email:"${email}", password:"${password}"){ token } }` - const data = await request(host, mutation) - const { token } = data.login + const response = await request(host, mutation) + const { token } = response.login + if(!token) throw `Could not get a JWT token from the backend:\n${response}` return token } + +export async function authenticatedGraphQLClient(params){ + const jwt = await getJWT(params) + const options = { + headers: { + 'Authorization': `Bearer ${jwt}` + } + } + return new GraphQLClient(host, options) +} diff --git a/src/middleware/permissionsMiddleware.spec.js b/src/middleware/permissionsMiddleware.spec.js index 9da3a3e9d..e88362a34 100644 --- a/src/middleware/permissionsMiddleware.spec.js +++ b/src/middleware/permissionsMiddleware.spec.js @@ -1,6 +1,5 @@ -import { GraphQLClient } from 'graphql-request' import { create, cleanDatabase } from '../seed/factories' -import { host, login } from '../jest/helpers' +import { authenticatedGraphQLClient } from '../jest/helpers' describe('authorization', () => { describe('given two existing users', () => { @@ -20,15 +19,10 @@ describe('authorization', () => { }) describe('logged in', () => { - let jwt, graphQLClient + let graphQLClient beforeEach(async () => { - jwt = await login({ email: 'test@example.org', password: '1234' }) - graphQLClient = new GraphQLClient(host, { - headers: { - authorization: `Bearer ${jwt}` - } - }) + graphQLClient = await authenticatedGraphQLClient({ email: 'test@example.org', password: '1234' }) }) describe('query email', () => { @@ -43,7 +37,6 @@ describe('authorization', () => { it('exposes the owner\'s email address', async () => { const data = await graphQLClient.request(query({ email: 'test@example.org' })) - console.log(process.env) expect(data).toEqual({ User: [ { email: 'test@example.org' } ] }) }) })