'use strict' const test = require('ava') const { stub } = require('sinon') const Hapi = require('@hapi/hapi') const UserService = require('../lib/services/user.js') const plugin = require('../lib/plugins/user.js') const User = require('../lib/models/user.js') const Auth = require('../lib/models/authentication.js') const payload = { user_name: 'john_doe', user_email: 'test@testemail.com', is_poster: 1, user_pass: 'password', } const mockInsert = { ...payload, id: 15, is_admin: 0, is_verified: 1, } const mockReturn = { is_admin: 0, is_poster: 1, is_verified: 1, user_email: 'test@testemail.com', user_id: 15, user_name: 'john_doe', } const pathToTest = { method: 'POST', url: '/signup', payload: JSON.stringify(payload), } test('path /signup should return new user info', async t => { /** * Create a new server and register services, * models and routes for testing * - * NOTE: We use a mocked registerModel() and register * models manually. Normally this is handled by * Schwifty at runtime. */ const server = Hapi.server() /** * Overload so we don't register any models * using the plugin call (see plugins/profile.js) * and Manually load the model we need for the test */ server.registerModel = () => {} server.models = () => ({ User, Auth }) // TODO: Apply server.registrations to other test specs server.registrations = { 'main-app-plugin': { options: {}, }, } /** * Register Routes and Services as usual */ await plugin.register(server) server.services()['userService'] = new UserService(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({ where: () => { if (mockInsert.user_email !== 'test@testemail.com') { return [mockInsert.user_email] } else return [] }, insert: () => mockInsert, }) stub(server.models()['Auth'], 'query').returns({ insert: () => mockInsert, throwIfNotFound: () => ({ where: () => ({ patch: () => ({}), }), }), }) /** * 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() })