Back to Repositories

Testing AST Node Object Conversion in GatsbyJS

This test suite validates the functionality of the getObjectFromNode utility in Gatsby Recipes, which converts AST nodes into JavaScript objects. The tests ensure accurate parsing and transformation of complex object structures with nested properties and various data types.

Test Coverage Overview

The test coverage focuses on validating AST node to object conversion functionality.

  • Tests object structure preservation
  • Verifies handling of multiple data types (strings, numbers, arrays)
  • Validates nested object conversion
  • Covers template literal processing

Implementation Analysis

The testing approach uses Jest’s snapshot testing capabilities to verify object transformation accuracy. The implementation leverages Babel’s template functionality to create test fixtures, demonstrating a practical approach to AST-based testing.

The test utilizes template strings and AST manipulation to create complex test scenarios.

Technical Details

  • Jest testing framework
  • Babel template utility
  • AST node manipulation
  • Inline snapshot testing
  • Object structure validation

Best Practices Demonstrated

The test exhibits several testing best practices including isolated test cases, clear fixture setup, and snapshot testing for complex object validation. The code organization separates fixture creation from test execution, promoting reusability and maintainability.

  • Clean fixture setup
  • Snapshot testing for complex objects
  • Clear test case isolation

gatsbyjs/gatsby

deprecated-packages/gatsby-recipes/src/providers/gatsby/utils/get-object-from-node.test.js

            
import template from "@babel/template"

import getObjectFromNode from "./get-object-from-node"

const buildFixture = () => {
  const ast = template(`
    const foo = {
      foo: \`bar\`,
      "baz": 123,
      "qux": [
        {
          foo: 'bar'
        },
        'baz',
        12.34
      ]
    }
  `)()

  return ast.declarations[0].init
}

test(`get-object-from-node return object from AST node`, () => {
  const result = getObjectFromNode(buildFixture())

  expect(result).toMatchInlineSnapshot(`
    Object {
      "baz": 123,
      "foo": "bar",
      "qux": Array [
        Object {
          "foo": "bar",
        },
        "baz",
        12.34,
      ],
    }
  `)
})