Back to Repositories

Testing v-On Directive Transformation in dcloudio/uni-app MP Compiler

This test suite focuses on validating the v-on directive transformation in the uni-app MP compiler, specifically for handling dynamic event bindings. It ensures proper error handling and validation of event binding syntax in the Vue template compilation process.

Test Coverage Overview

The test coverage focuses on error handling for dynamic event bindings in the v-on directive implementation.

  • Tests dynamic event binding validation
  • Verifies error code generation for invalid syntax
  • Validates location tracking in error reporting

Implementation Analysis

The testing approach utilizes Jest’s mocking capabilities to verify compiler error handling. It implements a custom parseWithVOn helper function that wraps the compilation process and returns both AST root and first node for detailed assertion checking.

  • Uses mock functions to capture error callbacks
  • Implements AST-based validation
  • Leverages Vue compiler core types

Technical Details

Testing infrastructure includes:

  • Jest test framework
  • Vue compiler-core integration
  • Custom error code enumeration (MPErrorCodes)
  • AST parsing utilities
  • Location tracking validation

Best Practices Demonstrated

The test suite demonstrates several testing best practices for compiler implementations.

  • Isolated test helper functions
  • Precise error condition verification
  • Structured error object validation
  • Clear test case organization
  • Type-safe testing approach

dcloudio/uni-app

packages/uni-mp-compiler/__tests__/vOn.mp.spec.ts

            
import type { ElementNode } from '@vue/compiler-core'
import { compile } from '../src'
import { MPErrorCodes } from '../src/errors'
import type { CompilerOptions } from '../src/options'

function parseWithVOn(template: string, options: CompilerOptions = {}) {
  const { ast } = compile(template, {
    generatorOpts: {
      concise: true,
    },
    ...options,
  })
  return {
    root: ast,
    node: ast.children[0] as ElementNode,
  }
}

describe('compiler(mp): transform v-on', () => {
  test('should error if dynamic event', () => {
    const onError = jest.fn()
    parseWithVOn(`<div v-on:[event]="onClick" />`, { onError })
    expect(onError.mock.calls[0][0]).toMatchObject({
      code: MPErrorCodes.X_V_ON_DYNAMIC_EVENT,
      loc: {
        start: {
          line: 1,
          column: 6,
        },
        end: {
          line: 1,
          column: 28,
        },
      },
    })
  })
})