测试组件路由器链接

时间:2020-10-13 18:45:21

标签: javascript reactjs testing jestjs react-router-dom

我正在尝试测试包装在react-router-dom的Link组件中的组件,该组件如下所示:

// PokemonItem/index.js

import React from 'react';
import { Link } from 'react-router-dom';

const PokemonItem = ({ pokemon }) => {
  const {
    id, img, name, number, types,
  } = pokemon;
  return (
    <Link to={{
      pathname: `/pokemon-details/${id}`,
      state: { pokemon },
    }}
    >
      <div className="pokemon-card">
        <header className="card-header">
          <img src={img} alt={name} />
        </header>
        <main className="card-body">
          <h6>
            #
            {number}
          </h6>
          <h2>{name}</h2>
        </main>
      </div>
    </Link>
  );
};

export default PokemonItem;

我使用了反应测试库的示例来创建我的测试文件:

https://testing-library.com/docs/example-react-router

这是我的测试文件:

import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createMemoryHistory } from 'history'
import React from 'react'
import { Router } from 'react-router-dom'

import '@testing-library/jest-dom/extend-expect'

import PokemonItem from '../components/PokemonItem';

test('full app rendering/navigating', () => {
  const history = createMemoryHistory();
  const pokemonItem = {
    id: 1,
    name: 'Bulbasaur',
    number: '#001',
    img: '',
    types: [],
    height: 10
  };

  render(
    <Router history={history}>
      <PokemonItem pokemon={pokemonItem} />
    </Router>
  );

  expect(screen.getByText(/bulbasaur/i)).toBeInTheDocument();

  const leftClick = { button: 0 };
  userEvent.click(screen.getByText(/bulbasaur/i), leftClick);

  expect(screen.getByText(/height/i)).toBeInTheDocument();
});

click事件应重定向到仅包含文本“高度”的组件,这是我的PokemonDetails页面,但未成功。

这是控制台上显示的错误:

Unable to find an element with the text: /height/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    <body>
      <div>
        <a
          href="/pokemon-details/1"
        >
          <div
            class="pokemon-card"
          >
            <header
              class="card-header"
            >
              <img
                alt="Bulbasaur"
                src=""
              />
            </header>
            <main
              class="card-body"
            >
              <h6>
                #
                #001
              </h6>
              <h2>
                Bulbasaur
              </h2>
            </main>
            <footer
              class="card-footer"
            />
          </div>
        </a>
      </div>
    </body>

      62 | 
      63 |   // check that the content changed to the new page
    > 64 |   expect(screen.getByText(/height/i)).toBeInTheDocument();
         |                 ^
      65 | })

它没有被重定向到详细信息页面。

我尝试了很多教程,并尝试了多种模拟点击的方法,包括fireEvent.click方法,但均未成功。我还需要做什么?

0 个答案:

没有答案