Back to Repositories

Testing Deterministic JSON Stringify Implementation in Insomnia

This test suite validates the deterministicStringify utility function in the Insomnia project, ensuring consistent JSON string output regardless of input object structure. The tests verify key sorting, recursive handling, and special type management.

Test Coverage Overview

The test suite provides comprehensive coverage of the deterministicStringify function.

Key areas tested include:
  • Object key sorting functionality
  • Recursive handling of nested objects and arrays
  • Special type handling (Date objects, null values)
  • Non-JSON type exclusion

Implementation Analysis

The testing approach uses Jest’s describe/it pattern for clear test organization. Each test case isolates specific functionality, from basic key sorting to complex nested structures. The implementation leverages Jest’s expect assertions with precise string matching to validate output format.

Technical Details

Testing tools and configuration:
  • Framework: Vitest/Jest
  • Test Type: Unit tests
  • Language: TypeScript
  • Key Methods: describe(), it(), expect()
  • Assertion Style: toBe() for strict equality checking

Best Practices Demonstrated

The test suite exemplifies several testing best practices.

Notable aspects include:
  • Isolated test cases for specific functionality
  • Clear test descriptions
  • Comprehensive edge case coverage
  • Consistent assertion patterns
  • Logical test progression from simple to complex scenarios

kong/insomnia

packages/insomnia/src/sync/lib/__tests__/deterministicStringify.test.ts

            
import { describe, expect, it } from 'vitest';

import { deterministicStringify } from '../deterministicStringify';

describe('deterministicStringify()', () => {
  it('sorts object keys', () => {
    const result = deterministicStringify({
      c: 'c',
      a: 'a',
      b: 'b',
    });
    expect(result).toBe('{"a":"a","b":"b","c":"c"}');
  });

  it('works recursively', () => {
    const result = deterministicStringify({
      arr: [
        {
          b: 'b',
          a: 'a',
        },
      ],
      obj: {
        obj2: {
          b: 'b',
          a: 'a',
        },
      },
    });
    expect(result).toBe('{"arr":[{"a":"a","b":"b"}],"obj":{"obj2":{"a":"a","b":"b"}}}');
  });

  it('works with strange types', () => {
    const sDate = deterministicStringify(new Date(1541178019555));
    expect(sDate).toBe('"2018-11-02T17:00:19.555Z"');
    const sNull = deterministicStringify(null);
    expect(sNull).toBe('null');
  });

  it('skips non-json types', () => {
    const sFunc = deterministicStringify({
      a: [0, () => null],
      fn: () => null,
    });
    expect(sFunc).toBe('{"a":[0]}');
  });
});