Skip to main content

Node.js API Tests

Complete guide to the Node.js API test suite for hlquery.

Overview

The Node.js API includes 31 comprehensive test scripts that verify all aspects of the hlquery API using the Node.js client library. Each test is self-contained, creates its own test data when needed, and cleans up afterward.

Quick Start

Running Individual Tests

cd api/node/tests
node test_get_document.js
node test_search.js
node test_filter_search.js

Running All Tests

cd api/node/tests
node run_all_tests.js

Test Structure

Common Test Pattern

All Node.js tests follow this self-contained pattern:

#!/usr/bin/env node
/**
* Test Name
*
* WHAT THIS TEST DOES:
* 1. Step-by-step description
* 2. What it tests
* 3. What it verifies
*
* HOW TO RUN:
* node test_name.js
*/

const Client = require('../lib/Client');

const BASE_URL = 'http://localhost:9200';

// Helper functions (assert, displayResponse)
// Main async test function
// Cleanup logic

Key Features

  • Self-Contained: Tests create their own data if needed
  • Automatic Cleanup: Test data is removed after tests
  • Clear Output: Uses indicators and detailed status
  • Error Handling: Proper error handling with cleanup
  • Exit Codes: Returns 0 on success, 1 on failure

Available Tests

Core CRUD Operations

test_create_collection.js

Purpose: Tests creating collections with schemas

What it tests:

  • Creating a collection with field definitions
  • Verifying collection exists after creation
  • Collection schema validation

Key Concepts:

  • Schema defines what fields documents can have
  • Field types: string, int32, float, bool, string[], float[]
  • Collections must have unique names

test_get_collection.js

Purpose: Retrieves collection details and schema information

What it tests:

  • Getting collection metadata
  • Retrieving collection fields
  • Handling non-existent collections

test_update_collection.js

Purpose: Updates collection schemas

What it tests:

  • Modifying collection field definitions
  • Schema update validation

test_delete_collection.js

Purpose: Deletes collections and verifies deletion

What it tests:

  • Collection deletion
  • Verification that collection no longer exists
  • Error handling for already-deleted collections

Document Operations

test_docs_insert.js

Purpose: Tests inserting documents into collections

What it tests:

  • Creating collections with schemas
  • Inserting documents with various field types
  • Verifying documents were inserted correctly

Key Code Pattern:

// Create collection
const schema = {
fields: [
{ name: 'title', type: 'string' },
{ name: 'content', type: 'string' },
{ name: 'tags', type: 'string[]' }
]
};
const createResp = await client.collections().create(collectionName, schema);

// Insert document
const doc = {
id: 'doc_123',
title: 'Test Document',
content: 'Content here',
tags: ['tag1', 'tag2']
};
const addResp = await client.documents().add(collectionName, doc);

test_get_document.js

Purpose: Retrieves individual documents by ID

What it tests:

  • Getting documents by ID
  • Document structure validation
  • Error handling for non-existent documents

test_update_document.js

Purpose: Updates existing documents

What it tests:

  • Updating document fields
  • Verifying updates were applied
  • Partial updates (updating only some fields)

test_delete_document.js

Purpose: Deletes documents from collections

What it tests:

  • Document deletion
  • Verification that document no longer exists
  • Cleanup of test data

test_list_documents.js

Purpose: Lists documents with pagination

What it tests:

  • Listing all documents in a collection
  • Pagination (offset/limit)
  • Response structure validation

Search Operations

test_search.js

Purpose: Basic search functionality

What it tests:

  • Text search across fields
  • Wildcard searches
  • Search with filters
  • Search with sorting
  • Search with pagination
  • Search result structure

Key Concepts:

  • q parameter: search query string
  • query_by: fields to search in (comma-separated)
  • limit: maximum number of results

test_filter_search.js

Purpose: Search with filter conditions

What it tests:

  • Simple filters (category:test)
  • Multiple filters with AND (category:test && status:active)
  • Numeric filters (price:>15)
  • OR filters (category:test || category:premium)
  • Filters combined with sorting

Filter Syntax Examples:

// Simple filter
{ filter_by: 'category:test' }

// AND filter
{ filter_by: 'category:test && status:active' }

// OR filter
{ filter_by: 'category:test || category:premium' }

// Numeric comparison
{ filter_by: 'price:>15' }
{ filter_by: 'price:<=100' }

test_sort_search.js

Purpose: Search with sorting

What it tests:

  • Ascending sort (sort_by => 'price:asc')
  • Descending sort (sort_by => 'price:desc')
  • Multiple field sorting

test_multi_search.js

Purpose: Multi-collection search

What it tests:

  • Searching across multiple collections simultaneously
  • Handling multiple search results
  • Result aggregation

Example:

const searches = [
{ collection: 'products', q: 'laptop', query_by: 'title' },
{ collection: 'articles', q: 'laptop', query_by: 'content' }
];
const results = await client.searchApi().multiSearch(searches);

test_vector_search.js

Purpose: Vector similarity search

What it tests:

  • Creating collections with vector fields (float[])
  • Inserting documents with embedding vectors
  • Performing vector similarity searches
  • Vector query parameters (threshold, normalize)

test_pagination.js

Purpose: Pagination in searches and listings

What it tests:

  • Offset/limit pagination
  • Multiple pages of results
  • Pagination in both search and list operations

test_facets.js

Purpose: Faceted search results

What it tests:

  • Facet counts by field
  • Facet aggregation
  • Facet response structure

test_search_cols.js

Purpose: Search within collections

What it tests:

  • Collection-specific search
  • Search result structure

Bulk Operations

test_import_documents.js

Purpose: Bulk document import

What it tests:

  • Importing multiple documents at once
  • Bulk import response handling
  • Verifying all documents were imported

Example:

const docs = [
{ id: 'doc1', title: 'Doc 1' },
{ id: 'doc2', title: 'Doc 2' },
{ id: 'doc3', title: 'Doc 3' }
];
const result = await client.documents().import(collectionName, docs);

test_bulk_operations.js

Purpose: Various bulk operations

What it tests:

  • Bulk document operations
  • Batch processing
  • Performance with large datasets

Advanced Features

test_aliases.js

Purpose: Collection alias management

What it tests:

  • Alias creation and management
  • Using aliases in queries
  • Alias endpoints (if available)

test_auth.js

Purpose: Authentication functionality

What it tests:

  • Health check without authentication
  • Bearer token authentication
  • API key authentication
  • Token validation

Example:

// Set bearer token
client.setAuthToken('your_token', 'bearer');

// Clear authentication
client.clearAuth();

test_data_types.js

Purpose: Various data types

What it tests:

  • String fields
  • Integer fields (int32)
  • Float fields
  • Boolean fields
  • Array fields (string[], float[])

test_edge_cases.js

Purpose: Edge cases and special scenarios

What it tests:

  • Empty queries
  • Very long collection names
  • Non-existent resources
  • Special characters

test_error_handling.js

Purpose: Error handling

What it tests:

  • Invalid collection names
  • Invalid document IDs
  • Error response detection
  • Exception handling

test_export.js

Purpose: Document export

What it tests:

  • Exporting collections
  • Export formats
  • Export endpoints (if available)

test_overrides.js

Purpose: Search override management

What it tests:

  • Creating search overrides
  • Override endpoints (if available)
  • Override functionality

test_stopwords.js

Purpose: Stopword management

What it tests:

  • Stopword configuration
  • Stopword endpoints (if available)
  • Stopword functionality

test_synonyms.js

Purpose: Synonym management

What it tests:

  • Synonym configuration
  • Synonym endpoints (if available)
  • Synonym functionality

System Tests

test_health.js

Purpose: Health and status endpoints

What it tests:

  • /health endpoint
  • /status endpoint
  • /metrics endpoint
  • Response consistency

test_stats.js

Purpose: Server statistics

What it tests:

  • Basic stats endpoint
  • Detailed statistics
  • Cache statistics
  • Connection statistics
  • RocksDB Statistics

test_list_all_cols.js

Purpose: List all collections

What it tests:

  • Listing collections with pagination
  • Collection metadata
  • Collection counts

Understanding Test Output

Success Indicators

  • Green checkmark: Test assertion passed
  • Red X: Test assertion failed
  • Chart icon: API response display
  • Checkmark: Operation completed successfully
  • Warning: Non-critical issue or information

Test Summary

Each test ends with a summary:

----------------------------------------------------------------==============================
Test Summary: 5 passed, 0 failed
----------------------------------------------------------------==============================
  • Exit code 0: All tests passed
  • Exit code 1: One or more tests failed

Common Patterns

Pattern 1: Self-Contained Test Data

// Find or create test collection
let collectionName = null;
const collectionsResp = await client.listCollections(0, 10);

if (!collectionName) {
// Create test collection
collectionName = 'test_' + Math.floor(Date.now() / 1000);
const schema = { fields: [...] };
await client.collections().create(collectionName, schema);
createdTestCollection = true;
}

// Run tests...

// Cleanup
if (createdTestCollection) {
await client.collections().delete(collectionName);
}

Pattern 2: Error Handling

try {
// Test code here
} catch (error) {
console.log(`\nFatal error: ${error.message}`);
console.error(error);
testsFailed++;

// Cleanup on error
if (createdTestCollection && collectionName) {
try {
await client.collections().delete(collectionName);
} catch (e) {
// Ignore cleanup errors
}
}
}

Pattern 3: Response Validation

const response = await client.getDocument(collectionName, docId);

// Check status code
if (response.getStatusCode() === 200) {
const body = response.getBody();

// Validate structure
if (body !== null && typeof body === 'object' && body.id) {
// Test passed
}
}

Helper Functions

All tests include these helper functions:

assert(condition, message)

Asserts a condition and prints pass/fail.

if (assert(response.getStatusCode() === 200, 'Request successful')) {
testsPassed++;
} else {
testsFailed++;
}

displayResponse(testName, response, showBody)

Displays API response in readable format.

displayResponse('GET /collections/my_col', response);
// Shows:
// GET /collections/my_col
// Status: 200
// Response: { ... formatted JSON ... }

Troubleshooting

Test Fails with Connection Error

Problem: Cannot connect to server

Solution:

  1. Check if server is running: curl http://localhost:9200/health
  2. Verify BASE_URL in test file matches your server
  3. Check firewall/network settings

Test Creates Data But Doesn't Clean Up

Problem: Test data remains after test

Solution:

  • Tests should clean up automatically
  • If cleanup fails, manually delete test collections:
    await client.collections().delete('test_collection_name');

Module Not Found Errors

Problem: Cannot find Client module

Solution:

  • Ensure you're running from the test directory
  • Check that lib/Client.js exists in api/node/lib/
  • Verify Node.js version (>= 12.0.0)

Best Practices

When Writing New Tests

  1. Use self-contained pattern: Create test data if needed
  2. Always cleanup: Delete test collections/documents
  3. Handle errors: Use try-catch blocks with cleanup
  4. Clear output: Use helper functions for consistent formatting
  5. Exit codes: Return 0 on success, 1 on failure
  6. Add comments: Explain what the test does and why

Test Data Naming

Use timestamp-based names to avoid conflicts:

const collectionName = 'test_feature_' + Math.floor(Date.now() / 1000);

Error Messages

Provide helpful error messages:

if (!collectionName) {
console.log(' No collections available - cannot run tests');
console.log(' Create a collection first\n');
}

Contributing

When adding new tests:

  1. Follow the existing test pattern
  2. Add comprehensive comments
  3. Include cleanup logic
  4. Test error cases
  5. Update this documentation

Support

For issues with Node.js tests:

  • Check server is running and accessible
  • Verify Node.js version (>= 12.0.0)
  • Review test output for specific error messages
  • Check server logs for detailed errors