Back to Repositories

Testing Subdomain Processing Implementation in koajs/koa

This test suite validates subdomain handling functionality in Koa.js request objects, focusing on extracting and processing subdomain arrays from host headers. It ensures proper subdomain parsing across different configurations and edge cases.

Test Coverage Overview

The test suite provides comprehensive coverage of subdomain extraction functionality:
  • Validates multi-level subdomain parsing with configurable offset
  • Tests empty host header scenarios
  • Verifies IP address handling with ports
  • Covers edge cases in hostname processing

Implementation Analysis

The testing approach utilizes Node’s native test framework with assert module for verification. It implements isolated request object testing through mock contexts, allowing granular control over header values and application configuration.

The tests follow a clear pattern of request object setup, header manipulation, and assertion verification.

Technical Details

Testing tools and configuration:
  • Node.js native test framework
  • Assert module for assertions
  • Custom test helpers for request context creation
  • Mock request objects with configurable headers
  • Subdomain offset configuration testing

Best Practices Demonstrated

The test suite exemplifies several testing best practices:
  • Isolated test cases with clear separation of concerns
  • Comprehensive edge case coverage
  • Consistent test structure and organization
  • Effective use of mock objects
  • Clear assertion messages and expectations

koajs/koa

__tests__/request/subdomains.test.js

            
'use strict'

const { describe, it } = require('node:test')
const assert = require('assert')
const request = require('../../test-helpers/context').request

describe('req.subdomains', () => {
  it('should return subdomain array', () => {
    const req = request()
    req.header.host = 'tobi.ferrets.example.com'
    req.app.subdomainOffset = 2
    assert.deepStrictEqual(req.subdomains, ['ferrets', 'tobi'])

    req.app.subdomainOffset = 3
    assert.deepStrictEqual(req.subdomains, ['tobi'])
  })

  it('should work with no host present', () => {
    const req = request()
    assert.deepStrictEqual(req.subdomains, [])
  })

  it('should check if the host is an ip address, even with a port', () => {
    const req = request()
    req.header.host = '127.0.0.1:3000'
    assert.deepStrictEqual(req.subdomains, [])
  })
})