import ava, { TestInterface } from 'ava'; import { Mongoose } from 'mongoose'; import { AuthenticationError } from 'apollo-server-micro'; import { Factory } from '../../../database/factory'; import * as testUtils from '../../../test/utils'; import { User } from '../../../app/user'; import { createContext } from '../../../test/utils/create-mock-context'; import { gqlCall } from '../../../test/utils/gqlCall'; import { defineUserAbility } from '../../../server/authorization/user-authorization'; // // Setup // const test = ava as TestInterface<{ db: Mongoose }>; test.before(async t => { await testUtils.setupDB(t); }); test.afterEach.always(async t => { await testUtils.cleanupDB(t); }); test.after.always(async t => { await testUtils.tearDownDB(t); }); // ** Constants const createRecipeMutation = ` mutation Create($recipe: CreateRecipeInput!) { createRecipe(input: $recipe) { id title } } `; // // Tests // test.serial('Should save recipe to DB', async t => { const user = await Factory.create('user'); const context = createContext({ state: { user, abilities: defineUserAbility(user) }, }); let recipeCount = await user.getRecipes().countDocuments(); t.is(recipeCount, 0); const response = await gqlCall({ source: createRecipeMutation, contextValue: context, variableValues: { recipe: { title: 'A test Recipe', }, }, }); recipeCount = await user.getRecipes().countDocuments(); t.falsy(response.errors); t.is(recipeCount, 1); }); test.serial('Should return the created recipe', async t => { const recipe = { title: 'A test Recipe', }; const user = await Factory.create('user'); const context = createContext({ state: { user, abilities: defineUserAbility(user) }, }); const response = await gqlCall({ source: createRecipeMutation, contextValue: context, variableValues: { recipe, }, }); t.is(response.data.createRecipe.title, recipe.title); }); test.serial( 'Should return an error when the user is not logged in', async t => { const context = createContext({ state: { user: null } }); const response = await gqlCall({ source: createRecipeMutation, contextValue: context, variableValues: { recipe: { title: 'A test Recipe', }, }, }); t.truthy(response.errors.length > 0); t.true(response.errors[0].originalError instanceof AuthenticationError); } );