Skip to content

__PATH_PREFIX__ for testing with enzyme/jest #13115

@daniellizik

Description

@daniellizik

Related to #1378

I'm still seeing this in a enzyme/jest test:

gatsby-config.js

module.exports = {
  // this doesn't affect the test at all, it seems
  pathPrefix: ' '
};

test

import { render } from 'enzyme';
import { Link } from 'gatsby';

it('renders', () => {
  const wrapper = render(<Link to="/foo" />);
  // ReferenceError: __PATH_PREFIX__ is not defined
});

// this one is fine
it('provides the expected global', () => {
  global.__PATH_PREFIX__ = 'test';
  const wrapper = render(<Link to="/foo" />);
});

The docs on pathPrefix don't explicitly mention what to do during testing

During development, write paths as if there was no path prefix e.g. for a blog hosted at example.com/blog, don’t add /blog to your links. The prefix will be added when you build for deployment.

Maybe here it would be better to do something like

export function withPrefix(path) {
  const pathPrefix = typeof __PATH_PREFIX__ !== 'undefined' ? __PATH_PREFIX__ : '';
  return normalizePath(`${pathPrefix}/${path}`)
}

Probably a better solution would be to inject the global if NODE_ENV is test?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions