Back to Repositories

Testing Font Preload Implementation in GatsbyJS

This test suite validates the font preloading functionality in Gatsby’s server-side rendering (gatsby-ssr). It ensures proper handling of font assets and generation of link tags with appropriate crossorigin attributes for both external and self-hosted fonts.

Test Coverage Overview

The test suite provides comprehensive coverage of font preloading functionality.

Key areas tested include:
  • Empty asset handling
  • Link tag generation for multiple font types
  • External font loading with crossOrigin configurations
  • Self-hosted font handling
Integration points focus on the cache module and head component rendering system.

Implementation Analysis

The testing approach uses Jest’s mocking capabilities to simulate the cache loading system and verify head component generation.

Key patterns include:
  • Mock implementation for cache loading
  • Snapshot testing for link tag verification
  • Dynamic configuration testing for crossOrigin attributes
  • Function-based and string-based crossOrigin handling

Technical Details

Testing tools and setup:
  • Jest as the primary testing framework
  • Mock functions for cache and head components
  • Snapshot testing for markup verification
  • afterEach cleanup hooks
  • Modular test organization with describe blocks

Best Practices Demonstrated

The test suite exemplifies high-quality testing practices through thorough isolation and verification.

Notable practices include:
  • Proper test isolation with mock resets
  • Comprehensive edge case coverage
  • Clear test case organization
  • Effective use of Jest’s mock API
  • Snapshot testing for markup validation

gatsbyjs/gatsby

packages/gatsby-plugin-preload-fonts/src/__tests__/gatsby-ssr.test.js

            
const { load: loadCache } = require(`../prepare/cache`)
const { onRenderBody } = require(`../gatsby-ssr`)

jest.mock(`../prepare/cache`, () => {
  return {
    load: jest.fn(),
  }
})

const setCachedAssets = assets =>
  loadCache.mockImplementationOnce(() => {
    return {
      timestamp: 0,
      hash: `initial-run`,
      assets,
    }
  })

describe(`gatsby-ssr`, () => {
  const setHeadComponents = jest.fn()

  afterEach(() => {
    setHeadComponents.mockReset()
  })

  it(`does nothing if the pathname has no cached assets`, () => {
    setCachedAssets({})

    onRenderBody({ setHeadComponents, pathname: `/foo` }, {})

    expect(setHeadComponents).not.toHaveBeenCalled()
  })

  it(`generates a <link> tag for each asset`, () => {
    setCachedAssets({
      [`/foo`]: {
        [`/path/to/font.otf`]: true,
        [`https://foo.bar/path/to/another.ttf`]: true,
        [`https://foo.baz/path/to/another/font.woff`]: true,
      },
    })

    onRenderBody({ setHeadComponents, pathname: `/foo` }, {})

    expect(setHeadComponents.mock.calls[0][0]).toMatchSnapshot()
  })

  describe(`generates <link> tags with \`crossorigin\` prop for external fonts`, () => {
    it(`accepts string \`crossOrigin\` in plugin config`, () => {
      setCachedAssets({
        [`/foo`]: {
          [`https://foo.bar/path/to/font.otf`]: true,
        },
      })

      onRenderBody(
        { setHeadComponents, pathname: `/foo` },
        { crossOrigin: `use-credentials` }
      )
      expect(setHeadComponents.mock.calls[0][0]).toMatchSnapshot()
    })

    it(`accepts function \`crossOrigin\` in plugin config`, () => {
      const config = {
        crossOrigin: path => (path === `/foo` ? false : `use-credentials`),
      }

      setCachedAssets({
        [`/foo`]: {
          [`https://foo.bar/path/to/font.otf`]: true,
        },
      })
      onRenderBody({ setHeadComponents, pathname: `/foo` }, config)

      setCachedAssets({
        [`/bar`]: {
          [`https://foo.bar/path/to/another.woff`]: true,
        },
      })
      onRenderBody({ setHeadComponents, pathname: `/bar` }, config)

      expect(setHeadComponents.mock.calls[0][0]).toMatchSnapshot()
      expect(setHeadComponents.mock.calls[1][0]).toMatchSnapshot()
    })
  })

  it(`generates <link> tags with \`crossorigin\` \`anonymous\` prop for self-hosted fonts`, () => {
    setCachedAssets({
      [`/foo`]: {
        [`/font.otf`]: true,
      },
    })

    onRenderBody({ setHeadComponents, pathname: `/foo` })

    expect(setHeadComponents.mock.calls[0][0]).toMatchSnapshot()
  })
})