Friday, 17 May 2019

How to mock a variable within a function

I want to test a function in Node.js.My test will pass some parameters to the function and I will check what the function returns.In the function there are two variables. I'd like to mock what these variables are set to. Is that possible and if so, how is it done? I've hit on sinon and am trying to figure out if anything can be done with it.This is the function: users.listUsers = async (params, db) => { const { sName, sEmail } = params; let { sortBy, descending } = params; const { offset = 0, limit = 20 } = params; // Users const query = db.knex.select([ 'users.id', 'users.name', 'users.email', 'sup.id as sup_id', 'sup.title', ]).from('users') .count('cus_users.id') .leftJoin('sup_users', 'users.id', 'sup_users.user_id') .innerJoin('sup', 'sup.id', 'sup_users.sup_id') .innerJoin('cus', 'cus.sup_id', 'sup.id') .leftJoin('cus_users', function additionalAnd() { this.on('cus.id', 'cus_users.cus_id') .andOn('users.id', 'cus_users.user_id'); }) .groupByRaw('users.id, users.name, users.email, sup.id, sup.title'); if (sName) { query.where('users.name', 'ILIKE', `%${sName}%`); } if (sEmail) { query.where('users.email', 'ILIKE', `%${sEmail}%`); } if (sortBy && descending) { sortBy = ORDER_FIELDS.indexOf(sortBy) !== -1 ? sortBy : null; descending = String(descending).toLowerCase() === 'true' ? 'DESC' : 'ASC'; query.orderBy(sortBy, descending); } if (offset && limit) { query.offset(offset).limit(limit); } let users = await query.offset(offset).limit(limit); users = users.reduce((accumulator, item) => { if (accumulator[item.id]) { const group = accumulator[item.id]; group.sup.push({ id: item.sup_id, code: item.code, title: item.title, }); group.count = `${(+group.count) + (+item.count)}`; } else { accumulator[item.id] = item; accumulator[item.id].sup = []; accumulator[item.id].sup.push({ id: item.sup_id, code: item.code, title: item.title, }); delete accumulator[item.id].sup_id; delete accumulator[item.id].code; delete accumulator[item.id].title; } return accumulator; }, {}); users = Object.values(users); return users; }; Currently it fails on const query = db.knex.select([ as it returns undefined. I need to set that to something. I don't think it matters what as I then want to also set `users` to a specific value which I'll then use to determine and check for the correct response in my test. I'm not yet sure if this can be done but if it can I want to find out how to do it.

Submitted May 17, 2019 at 08:48AM by paulcarron

No comments:

Post a Comment