0

I'm trying to do some simple snapshot testing using React and Jest.

Initially I was getting this error: Invariant failed: You should not use <Link> outside a <Router>

After reading this question I updated my test and wrapped the component I'm testing in: <MemoryRouter>...</MemoryRouter>. Once I did this, I started getting a new error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. I have no idea what that means.

My test:

import React from "react";
import BookTile from "./BookTile";
import MemoryRouter from "react-router-dom";
import renderer from "react-test-renderer";

test("my test", () => {
    let book = {};
    const component = renderer.create(
        <MemoryRouter>
            <BookTile book={book} />
        </MemoryRouter>
    )
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
})

The component I'm testing:

import React from "react";

import {Link} from "react-router-dom";

export default function BookTile(props) {
    return (
        <Link to={`/book/${props.book.id}`}>
            <div className="book-tile" style={{'backgroundImage': `url(${process.env.REACT_APP_API_URL}/uploads/${props.book.cover_image_file_name})`}}>
                <div className='book-tile-title'>
                    {props.book.title}
                </div>
            </div>
        </Link>
    )
}

1 Answer 1

1

You are not importing memory router correctly. Here's how it should look like:

import {MemoryRouter} from 'react-router-dom'
Sign up to request clarification or add additional context in comments.

1 Comment

i am importing it like you suggest and getting the error...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.