import test from 'ava'; import { AuthenticationError } from 'apollo-server-micro'; import { Factory } from '../../../database/factory'; import { createContext } from '../../../test/utils/create-mock-context'; import * as testUtils from '../../../test/utils'; import { defineUserAbility } from '../../../server/authorization/user-authorization'; import { RecipeCollection } from '../collection-model'; import { Recipe } from '../../../app/recipe'; import { User } from '../../../app/user'; import { updateRecipeCollection } from '../schema/update-collection'; test.before(testUtils.setupDB); test.afterEach.always(testUtils.cleanupDB); test.after.always(testUtils.tearDownDB); // // Tests // test.serial( 'Should return RecipeCollection with Populated Recipes', async t => { const user = await Factory.create('user'); const context = createContext({ state: { user, abilities: defineUserAbility(user) }, }); const collection = await Factory.create( 'collection', {}, { user, recipeCount: 1 } ); let collectionCount = await RecipeCollection.countDocuments(); if (collectionCount !== 1) { t.fail('collection not properly created'); } const updatedCollection = await updateRecipeCollection( null, { input: { id: collection.id, name: 'New Name', }, }, context, null ); // Returned collection is updated t.true(updatedCollection.nodes[0].recipe instanceof Recipe); } ); test.serial('Should udpate RecipeCollection on DB', async t => { const user = await Factory.create('user'); const context = createContext({ state: { user, abilities: defineUserAbility(user) }, }); const collection = await Factory.create( 'collection', {}, { user } ); let collectionCount = await RecipeCollection.countDocuments(); if (collectionCount !== 1) { t.fail('collection not properly created'); } const updatedCollection = await updateRecipeCollection( null, { input: { id: collection.id, name: 'New Name', }, }, context, null ); const dbCollection = await RecipeCollection.findById(collection.id); // Returned collection is updated t.is(updatedCollection.name, 'New Name'); // Database is updated t.is(dbCollection.name, 'New Name'); }); test.serial( 'Should return an error when the user does not own the collection', async t => { const user = await Factory.create('user'); const collection = await Factory.create('collection'); const context = createContext({ state: { user, abilities: defineUserAbility(user) }, }); await t.throwsAsync(async () => { return updateRecipeCollection( null, { input: { id: collection.id, }, }, context, null ); }, AuthenticationError); } ); 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 updateRecipeCollection( null, { input: { id: '', }, }, context, null ); }, AuthenticationError); } );