Skip to content

How do I test next/link using Jest? I get an error in Link.prefetch #4012

@jcollum

Description

@jcollum
  • [x ] I have searched the issues of this repository and believe that this is not a duplicate.

Expected Behavior

Links can be used in tests that are run with Jest.

Current Behavior

 at throwIfNoRouter (node_modules/next/dist/lib/router/index.js:107:11)
      at Object.SingletonRouter.(anonymous function) [as prefetch] (node_modules/next/dist/lib/router/index.js:69:5)
      at Link.prefetch (node_modules/next/dist/lib/link.js:143:24)
      at Link.componentDidMount (node_modules/next/dist/lib/link.js:148:12)
      at commitLifeCycles (node_modules/react-dom/cjs/react-dom.development.js:8770:24)
      at commitAllLifeCycles (node_modules/react-dom/cjs/react-dom.development.js:9946:9)

Steps to Reproduce (for bugs)

  1. "next": "^5.0.1-canary.15",

  2. Create a component with a render method like that returns: (partial):

import Link from 'next/link';
...
render() {
...
    return (
<h3>{messages.LABEL}</h3>
            <ul>
              <li>
                <Link prefetch href={messages.LINK1_URL || ''}>
                  <a>{messages.LINK1_LABEL || ''}</a>
                </Link>
              </li>
              <li>

3.

import React from 'react';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import enzymify from 'expect-enzyme';
import IndexPage from '../../pages/index';

const {shallow, mount} = Enzyme;
Enzyme.configure({adapter: new Adapter()});

describe('Index', () => {
  it('Renders', () => {
    const messages = {
        LABEL: 'Maguffin'
    };

    const indexPage = mount(
      <IndexPage
        country="us"
        language="en"
        path="/"
        messageBases={messages}
      />
    );
  1. jest -t Index

Context

I'm trying to write a Jest test for a page that has a next/link on it.

Your Environment

Tech Version
next ^5.0.1-canary.15
node 9
OS OSX 10.12
browser n/a
etc

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