我具有用于列出用户数据的功能:
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;
};
我现在正尝试为其编写单元测试。我想创建一些模拟查询数据,并检查listUsers返回的内容相对于模拟数据是否正确。我不确定如何设置此模拟。我目前正在查看mock-knex
,可以看到如何创建模拟数据库。我不知道从那里去哪里。有人可以建议吗?
其他信息
这是我目前正在测试中的内容:
var knex = require('knex');
var mockDb = require('mock-knex');
var db = knex({
client: 'pg',
User: {}
});
mockDb.mock(db);
var tracker = mockDb.getTracker();
tracker.install();
tracker.on('query', (query) => {
query.response([
{ id: 17,
name: 'John Doe',
email: 'john@doe.com',
sup_id: 1,
title: 'Supplier One',
code: 'supplierOne',
count: '1'
}
]);
});
const params = {
sName: 'name',
sEmail: 'email',
sortBy: 'name',
descending: 'true',
offset: 0,
limit: 20,
};
it.only('should search users', () => {
return User.listUsers(params, mockDb)
.then((res) => {
});
})
});
});
当我运行它时,出现此错误:
TypeError: Cannot read property 'knex' of undefined
它发生在我的函数的这一行:
const query = db.knex.select([