'use strict' const test = require('ava') const { stub } = require('sinon') const Hapi = require('@hapi/hapi') const UserService = require('../lib/services/user.js') const ProfileService = require('../lib/services/profile/index.js') const plugin = require('../lib/plugins/user.js') const User = require('../lib/models/user.js') const Profile = require('../lib/models/profile.js') const Tag = require('../lib/models/tag.js') const Response = require('../lib/models/response.js') const params = { user_id: 102, } const payload = [ { response_key_id: 8, val: 'bobby@bob.com' }, { response_key_id: 9, val: 'password' }, { response_key_id: 7, val: 'fk' }, { response_key_id: 11, val: 'position' }, ] const mockProfile = { user_id: 102, id: 147, } const mockReturn = { user_id: 102, profile_id: 147, } const pathToTest = { method: 'POST', url: `/${params.user_id}/profile`, payload: JSON.stringify(payload), } test(`path /${params.user_id}/profile should return new profile info`, async t => { /** * Create a new server and register services, * models and routes for testing * - * NOTE: We use register models manually. * Normally this is handled by * Schwifty at runtime. */ const server = Hapi.server() server.registrations = { 'main-app-plugin': { options: {}, }, } /** * Register Routes and Services as usual */ await plugin.register(server) server.models = () => ({ User, Profile, Tag, Response, }) server.services()['userService'] = new UserService(server) server.services()['profileService'] = new ProfileService(server) /** * Replace Objection model methods with our own mock functions * !: Janky - might be better to temp knex sqlite instance */ stub(server.models()['User'], 'query').returns({ throwIfNotFound: () => ({ first: () => ({ where: () => mockProfile.user_id, }), }), }) stub(server.models()['Tag'], 'query').returns({}) stub(server.models()['Profile'], 'query').returns({ where: () => mockProfile.user_id, whereIn: () => ({ withGraphFetched: () => ({ withGraphFetched: () => ({ withGraphFetched: () => [], }), }), }), insert: () => mockProfile, }) stub(server.models()['Response'], 'query').returns({ insert: () => ({ profile_id: 147, response_key_id: 11, val: 'position', id: 3, }), }) /** * Test the server with registered models and services */ const { payload } = await server.inject(pathToTest) const res = JSON.parse(payload) t.deepEqual(res.ok, true) t.deepEqual(res.data, mockReturn) server.stop() })