Back to Repositories

Testing Configuration Options Management in Vue CLI

This test suite validates the configuration options management functionality in Vue CLI, focusing on loading, saving, and handling presets. The tests ensure proper handling of configuration file operations and preset management through a series of unit tests.

Test Coverage Overview

The test suite provides comprehensive coverage of Vue CLI’s options handling mechanisms.

Key areas tested include:
  • Loading default and existing configurations
  • Saving configuration options with validation
  • Managing preset configurations
  • Handling invalid or unknown configuration fields

Implementation Analysis

The testing approach utilizes Jest’s mocking capabilities to isolate filesystem operations and ensure consistent test behavior. The implementation follows a modular pattern with distinct test cases for each configuration operation.

Key patterns include:
  • File system mocking using jest.mock(‘fs’)
  • Isolated test cases for each configuration operation
  • Progressive state validation through multiple assertions

Technical Details

Testing tools and setup:
  • Jest as the primary testing framework
  • File system mocking for isolation
  • JSON configuration file handling
  • Preset management utilities

Best Practices Demonstrated

The test suite exemplifies several testing best practices in JavaScript unit testing.

Notable practices include:
  • Proper test isolation through mocking
  • Clear test case organization
  • Comprehensive state validation
  • Progressive complexity in test scenarios

vuejs/vue-cli

packages/@vue/cli/__tests__/options.spec.js

            
jest.mock('fs')

const fs = require('fs')
const {
  rcPath,
  loadOptions,
  saveOptions,
  savePreset
} = require('../lib/options')

test('load options', () => {
  expect(loadOptions()).toEqual({})
  fs.writeFileSync(rcPath, JSON.stringify({
    presets: {}
  }, null, 2))
  expect(loadOptions()).toEqual({
    presets: {}
  })
})

test('should not save unknown fields', () => {
  saveOptions({
    foo: 'bar'
  })
  expect(loadOptions()).toEqual({
    presets: {}
  })
})

test('save options', () => {
  // partial
  saveOptions({
    packageManager: 'yarn'
  })
  expect(loadOptions()).toEqual({
    packageManager: 'yarn',
    presets: {}
  })

  // replace
  saveOptions({
    presets: {
      foo: { a: 1 }
    }
  })
  expect(loadOptions()).toEqual({
    packageManager: 'yarn',
    presets: {
      foo: { a: 1 }
    }
  })
})

test('save preset', () => {
  savePreset('bar', { a: 2 })
  expect(loadOptions()).toEqual({
    packageManager: 'yarn',
    presets: {
      foo: { a: 1 },
      bar: { a: 2 }
    }
  })

  // should entirely replace presets
  savePreset('foo', { c: 3 })
  savePreset('bar', { d: 4 })
  expect(loadOptions()).toEqual({
    packageManager: 'yarn',
    presets: {
      foo: { c: 3 },
      bar: { d: 4 }
    }
  })
})