UNPKG

als-mongo-list

Version:

A flexible, lightweight MongoDB query utility for Node.js applications. Simplifies database operations with intuitive filtering, pagination, sorting, and field selection. Ideal for REST API endpoints, providing a primary List class that abstracts complex

163 lines (135 loc) 6.24 kB
const mongoose = require('mongoose'); const List = require('../lib/index'); const { it, describe, before, after, beforeEach } = require('node:test'); const assert = require('node:assert'); // Подключение к MongoDB перед тестами before(async () => { mongoose.set('strictQuery', false); await mongoose.connect('mongodb://127.0.0.1:27017/listtests'); }); // Отключение после всех тестов after(async () => { await mongoose.connection.db.dropDatabase(); await mongoose.disconnect(); }); // Определяем схему и модель для тестов const testSchema = new mongoose.Schema({ name: String, age: Number, createdAt: Date, isActive: Boolean, }); const TestModel = mongoose.model('TestModel', testSchema); describe('Integration tests for List', () => { let list; beforeEach(async () => { // Очищаем и заполняем тестовыми данными перед каждым тестом await TestModel.deleteMany({}); await TestModel.insertMany([ { name: 'Alice', age: 25, createdAt: new Date(), isActive: true }, { name: 'Bob', age: 30, createdAt: new Date(), isActive: false }, { name: 'Charlie', age: 35, createdAt: new Date(), isActive: true }, ]); // Создаём экземпляр List перед каждым тестом list = new List(TestModel); list.searchIn('isActive', 'age', 'name').orderBy('age'); }); it('should retrieve all active records with pagination', async () => { const query = { currentPage: '0', pageSize: '2', isActive: 'true' }; const result = await list.exec(query); // console.log(result) // Проверяем результаты assert.strictEqual(result.total, 2); assert.strictEqual(result.query.currentPage, 0); assert.strictEqual(result.query.pageSize, 2); assert.strictEqual(result.items.length, 2); assert.strictEqual(result.items[0].name, 'Alice'); assert.strictEqual(result.items[1].name, 'Charlie'); }); it('should retrieve records by age range', async () => { const query = { age_gte: '30', age_lte: '35' }; const result = await list.exec(query); // Проверяем результаты assert.strictEqual(result.total, 2); assert.strictEqual(result.items.length, 2); assert.strictEqual(result.items[0].name, 'Bob'); assert.strictEqual(result.items[1].name, 'Charlie'); }); it('should apply sorting by age', async () => { const query = { orderBy: 'age' }; const result = await list.exec(query); // Проверяем, что данные отсортированы по возрасту assert.strictEqual(result.items.length, 3); assert.strictEqual(result.items[0].name, 'Alice'); assert.strictEqual(result.items[1].name, 'Bob'); assert.strictEqual(result.items[2].name, 'Charlie'); }); it('should handle search with regular expressions', async () => { const query = { name: 'Al' }; const result = await list.exec(query); // Проверяем результаты assert.strictEqual(result.total, 1); assert.strictEqual(result.items.length, 1); assert.strictEqual(result.items[0].name, 'Alice'); }); it('should return an empty result if search yields no matches', async () => { const query = { name: 'NonexistentName' }; const result = await list.exec(query); // Проверка на пустой массив `items` и корректную пагинацию assert.strictEqual(result.items.length, 0); assert.strictEqual(result.total, 0); }); it('should handle invalid `orderBy` gracefully', async () => { const query = { orderBy: 'invalidKey' }; const result = await list.exec(query); // Проверяем, что сортировка не применилась assert.strictEqual(result.items.length, 3); assert.strictEqual(result.items[0].name, 'Alice'); }); describe('Tests for large datasets', () => { const largeTestSchema = new mongoose.Schema({ name: String, age: Number, createdAt: Date, isActive: Boolean, }); const LargeTestModel = mongoose.model('LargeTestModel', largeTestSchema); let largeList; beforeEach(async () => { await LargeTestModel.deleteMany({}); const testData = Array.from({ length: 200 }).map((_, i) => ({ name: `User${i + 1}`, age: 20 + (i % 30), createdAt: new Date(), isActive: i % 2 === 0, })); await LargeTestModel.insertMany(testData); largeList = new List(LargeTestModel); largeList.searchIn('isActive', 'age', 'name').orderBy('age'); }); it('should retrieve paginated records with pageSize limit', async () => { const query = { currentPage: '2', pageSize: '20' }; const result = await largeList.exec(query); assert.strictEqual(result.total, 200); assert.strictEqual(result.query.currentPage, 2); assert.strictEqual(result.query.pageSize, 20); assert.strictEqual(result.items.length, 20); }); it('should retrieve filtered records by age range in large dataset', async () => { const query = { age_gte: '25', age_lte: '30' }; const result = await largeList.exec(query); assert.ok(result.total > 0); result.items.forEach(item => { assert.ok(item.age >= 25 && item.age <= 30); }); }); it('should apply sorting on large dataset', async () => { const query = { currentPage: '1', pageSize: '10', orderBy: '-age' }; const result = await largeList.exec(query); assert.strictEqual(result.items.length, 10); for (let i = 0; i < result.items.length - 1; i++) { assert.ok(result.items[i].age <= result.items[i + 1].age); } }); }); });