import test from 'ava'; import { AuthenticationError, UserInputError } from 'apollo-server-micro'; import { Factory } from '../../../database/factory'; import * as testUtils from '../../../test/utils'; import { createContext } from '../../../test/utils/create-mock-context'; import { defineUserAbility } from '../../../server/authorization/user-authorization'; import { RecipeCollection } from '../collection-model'; import { Recipe } from '../../recipe'; import { User } from '../../../app/user'; import { updateRecipeInCollection } from '../schema/update-recipe'; test.before(testUtils.setupDB); test.afterEach.always(testUtils.cleanupDB); test.after.always(testUtils.tearDownDB); // // Tests // test.serial( 'Should udpate Recipe order within a Recipe Collection', async t => { const user = await Factory.create('user'); const context = createContext({ state: { user, abilities: defineUserAbility(user) }, }); const collection = await Factory.create( 'collection', {}, { user, recipeCount: 3 } ); const recipeId = collection.nodes[2].recipe.toHexString(); const updatedCollection = await updateRecipeInCollection( null, { input: { recipeId, recipeCollectionId: collection.id, order: 0, }, }, context, null ); const dbCollection = await RecipeCollection.findById(collection.id); t.is(updatedCollection.nodes[0].recipe.id, recipeId); t.is(dbCollection.nodes[0].recipe.toHexString(), recipeId); } ); test.serial('Should return udpated Recipe Collection', async t => { const user = await Factory.create('user'); const context = createContext({ state: { user, abilities: defineUserAbility(user) }, }); const collection = await Factory.create( 'collection', {}, { user, recipeCount: 3 } ); const recipeId = collection.nodes[2].recipe.toHexString(); const updatedCollection = await updateRecipeInCollection( null, { input: { recipeId, recipeCollectionId: collection.id, order: 0, }, }, context, null ); t.true(updatedCollection instanceof RecipeCollection); t.true(updatedCollection.nodes[0].recipe instanceof Recipe); }); test.serial( 'Should throw error when the recipe is not present in the collection', async t => { const user = await Factory.create('user'); const context = createContext({ state: { user, abilities: defineUserAbility(user) }, }); const collection = await Factory.create( 'collection', {}, { user, recipeCount: 2 } ); const recipe = await Factory.create('recipe', { ownerId: user.id }); await t.throwsAsync(async () => { return updateRecipeInCollection( null, { input: { recipeCollectionId: collection.id, recipeId: recipe.id, order: 0, }, }, context, null ); }, UserInputError); } ); test.serial( 'Should return an error when the user is not logged in', async t => { const context = createContext({ state: { user: null, abilities: defineUserAbility(null) }, }); await t.throwsAsync(async () => { return updateRecipeInCollection( null, { input: { recipeCollectionId: '', recipeId: '', }, }, context, null ); }, AuthenticationError); } );