Back to Repositories

Testing Cookie Management Implementation in Koa.js

This test suite evaluates the cookie handling functionality in the Koa.js framework, focusing on setting and managing both signed and unsigned cookies. It verifies cookie operations in various scenarios including secure connections and proxy environments.

Test Coverage Overview

The test suite provides comprehensive coverage of Koa’s cookie management functionality.

Key areas tested include:
  • Setting unsigned cookies
  • Setting signed cookies with proper key configuration
  • Secure cookie handling in proxy environments
  • Cookie override functionality
Edge cases covered include error handling for signed cookies without keys and secure cookie behavior with X-Forwarded-Proto headers.

Implementation Analysis

The testing approach utilizes Jest’s describe/it blocks for structured test organization, combined with supertest for HTTP request simulation. The implementation follows a behavior-driven development pattern, testing both successful scenarios and error conditions.

The tests leverage async/await patterns for clean asynchronous testing and use the supertest library for middleware integration testing.

Technical Details

Testing tools and configuration:
  • Node’s built-in test runner (node:test)
  • Assert module for assertions
  • Supertest for HTTP testing
  • Koa application instance for each test
  • Custom middleware implementations
  • Proxy configuration testing

Best Practices Demonstrated

The test suite exemplifies several testing best practices in Node.js applications.

Notable practices include:
  • Isolated test contexts with fresh Koa instances
  • Proper async/await usage for asynchronous operations
  • Comprehensive error scenario coverage
  • Clear test case organization
  • Effective use of middleware for test scenarios

koajs/koa

__tests__/context/cookies.test.js

            
'use strict'

const { describe, it } = require('node:test')
const assert = require('assert')
const request = require('supertest')
const Koa = require('../..')

describe('ctx.cookies', () => {
  describe('ctx.cookies.set()', () => {
    it('should set an unsigned cookie', async () => {
      const app = new Koa()

      app.use((ctx, next) => {
        ctx.cookies.set('name', 'jon')
        ctx.status = 204
      })

      const res = await request(app.callback())
        .get('/')
        .expect(204)

      const cookie = res.headers['set-cookie'].some(cookie => /^name=/.test(cookie))
      assert.strictEqual(cookie, true)
    })

    describe('with .signed', () => {
      describe('when no .keys are set', () => {
        it('should error', () => {
          const app = new Koa()

          app.use((ctx, next) => {
            try {
              ctx.cookies.set('foo', 'bar', { signed: true })
            } catch (err) {
              ctx.body = err.message
            }
          })

          return request(app.callback())
            .get('/')
            .expect('.keys required for signed cookies')
        })
      })

      it('should send a signed cookie', async () => {
        const app = new Koa()

        app.keys = ['a', 'b']

        app.use((ctx, next) => {
          ctx.cookies.set('name', 'jon', { signed: true })
          ctx.status = 204
        })

        const res = await request(app.callback())
          .get('/')
          .expect(204)

        const cookies = res.headers['set-cookie']

        assert.strictEqual(cookies.some(cookie => /^name=/.test(cookie)), true)
        assert.strictEqual(cookies.some(cookie => /(,|^)name\.sig=/.test(cookie)), true)
      })
    })

    describe('with secure', () => {
      it('should get secure from request', async () => {
        const app = new Koa()

        app.proxy = true
        app.keys = ['a', 'b']

        app.use(ctx => {
          ctx.cookies.set('name', 'jon', { signed: true })
          ctx.status = 204
        })

        const res = await request(app.callback())
          .get('/')
          .set('x-forwarded-proto', 'https') // mock secure
          .expect(204)

        const cookies = res.headers['set-cookie']
        assert.strictEqual(cookies.some(cookie => /^name=/.test(cookie)), true)
        assert.strictEqual(cookies.some(cookie => /(,|^)name\.sig=/.test(cookie)), true)
        assert.strictEqual(cookies.every(cookie => /secure/.test(cookie)), true)
      })
    })
  })

  describe('ctx.cookies=', () => {
    it('should override cookie work', async () => {
      const app = new Koa()

      app.use((ctx, next) => {
        ctx.cookies = {
          set (key, value) {
            ctx.set(key, value)
          }
        }
        ctx.cookies.set('name', 'jon')
        ctx.status = 204
      })

      await request(app.callback())
        .get('/')
        .expect('name', 'jon')
        .expect(204)
    })
  })
})