快照测试错误:元素类型无效:预期为字符串[...]

时间:2020-05-26 03:46:37

标签: reactjs jestjs

我正在尝试使用React和Jest做一些简单的快照测试。

最初我遇到此错误:Invariant failed: You should not use <Link> outside a <Router>

阅读this question后,我更新了测试并将测试的组件包装在<MemoryRouter>...</MemoryRouter>中。完成此操作后,我开始收到一个新错误:Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.我不知道那是什么意思。

我的测试:

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();
})

我正在测试的组件:

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 个答案:

答案 0 :(得分:0)

您没有正确导入内存路由器。它的外观如下:

import {MemoryRouter} from 'react-router-dom'