question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot test <Link> outside of a Page on Next v9.5.0 (Enzyme + Jest)

See original GitHub issue

Bug report

Describe the bug

As of Next v9.5.0, Components which use the <Link> component cannot be tested in isolation. However, Pages which use <Link> can be tested fine.

To Reproduce

With this component:

// file: components/commonLink.tsx
import Link from "next/link";

export default function CommonLink() {
  return (
    <>
      <Link href="/other/page">
        <a>Click Me!</a>
      </Link>
    </>
  );
}

And this Test

// file: __tests__/components/commonLink.tsx
import { mount } from "enzyme";
import Component from "../../components/commonLink";

describe("navigation", () => {
  let wrapper;

  beforeEach(() => {
    wrapper = mount(<Component />);
  });

  afterEach(() => {
    wrapper.unmount();
  });

  test("renders", async () => {
    const html = wrapper.html();
    expect(html).toContain('href="/other/page">Click Me</a>');
  });
});

Produce the error:

    Error: Uncaught [TypeError: Cannot read property 'pathname' of null]
        at reportException (/Users/evan/workspace/grouparoo/grouparoo/core/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:62:24)
        at innerInvokeEventListeners (/Users/evan/workspace/grouparoo/grouparoo/core/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:333:9)
        at invokeEventListeners (/Users/evan/workspace/grouparoo/grouparoo/core/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)

...

        at Link (/Users/evan/workspace/grouparoo/grouparoo/core/node_modules/next/client/link.tsx:176:14)

...


    The above error occurred in the <Link> component:
        in Link (at commonLink.tsx:6)
        in CommonLink (created by WrapperComponent)
        in WrapperComponent

    Consider adding an error boundary to your tree to customize error handling behavior.
    Visit https://fb.me/react-error-boundaries to learn more about error boundaries.

      at logCapturedError (../node_modules/react-dom/cjs/react-dom.development.js:19527:21)
      at logError (../node_modules/react-dom/cjs/react-dom.development.js:19564:5)
      at update.callback (../node_modules/react-dom/cjs/react-dom.development.js:20708:5)
...

Expected behavior

The test should pass

In older versions of Next.js, this test passed.

Screenshots

N/A

System information

  • OS: OSX
  • Browser N/A
  • Version of Next.js: v9.5.0
  • Version of Node.js: v12, v14

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:27
  • Comments:17 (10 by maintainers)

github_iconTop GitHub Comments

7reactions
Timercommented, Jul 30, 2020

This was just fixed in 9.5.1, please upgrade!

7reactions
thebuildercommented, Jul 28, 2020

This is also an issue when using Storybook (or similar) to render components outside the page context.

Right now i’ve fixed it by creating a custom <RouterContext.Provider> to wrap the tests/stories.

.storybook/preview.js

import React from 'react'
import { addDecorator } from '@storybook/react'
import { linkTo } from '@storybook/addon-links'
import { RouterContext } from 'next/dist/next-server/lib/router-context'
import { startCase } from 'lodash'

addDecorator((storyFn) => (
  <RouterContext.Provider
    value={{
      pathname: '/',
      basePath: '',
      push: (url, as) => {
        if (as) linkTo('Routes', as !== '/' ? startCase(as) : 'Index')()
        return Promise.resolve(true)
      },
      replace: (url, as) => {
        if (as) linkTo('Routes', as !== '/' ? startCase(as) : 'Index')()
        return Promise.resolve(true)
      },
      reload: () => {},
      prefetch: () => {},
    }}
  >
    {storyFn()}
  </RouterContext.Provider>
))

For Testing Library I had to start using a custom render method, that wraps the application with the <RouterContext>.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Test Nextjs <Link /> with Jest + Testing-Library - Stack Overflow
When I'm testing the <Link /> behavior, expecting it to redirect to a certain route, there's a TypeError ( Cannot read property 'push'...
Read more >
Testing React Apps - Jest
Snapshot Testing with Mocks, Enzyme and React 16​ · Render as text. This way you won't see the props passed to the mock...
Read more >
Modern React testing, part 2: Jest and Enzyme - Artem Sapegin
You'll learn how to test React components with Jest and Enzyme and how to apply the best practices we've learned in the first...
Read more >
A Deep Dive on Managing Focus with React, Jest, and Enzyme
Use React ref to programmatically move focus between elements on a web page. Write tests using Jest and Enzyme to check focus management ......
Read more >
An in-depth beginner's guide to testing React applications in ...
React Testing Library vs Enzyme vs Jest ... The links in the header direct to other pages that are more of a placeholder...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found