简体   繁体   English

使用 react-testing-library 测试导航

[英]Testing navigation with react-testing-library

I want to test if a sidebar that I have created for navigation works or not, this is a simple example of what I have made我想测试我为导航创建的侧边栏是否有效,这是我所做的一个简单示例

<ul>
  <li><Link to="/location1">location 1</Link></li>
  <li><Link to="/location2">location 2</Link></li>
</ul>

this is my test这是我的测试

const routerWrapper = ({children}) => <BrowserRouter>{children}</BrowserRouter>

// The first one runs fine
it('navigation to location 1' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// get the element and click on it
// check if title of page is correct
})

it('navigation to location 2' , () => {
render(<SideBar/> , {wrapper:routerWrapper})
// can't run because location is at /location1
})

When I test the navigation with RTL, first test runs fine, but after that the location remains at that directory for next test, how do I clear location after every test?当我使用 RTL 测试导航时,第一次测试运行良好,但之后位置仍保留在该目录中以进行下一次测试,如何在每次测试后清除位置? or any suggestions how should I test navigation?或任何建议我应该如何测试导航?

Well I did figure it out, we can use <MemoryRouter> for this purpose.好吧,我确实想通了,我们可以为此目的使用<MemoryRouter> https://reactrouter.com/docs/en/v6/api#memoryrouter https://reactrouter.com/docs/en/v6/api#memoryrouter

Just passed the value ['/'] to initialEntries prop from <MemoryRouter> and tests work fine.只需将值 ['/'] 从<MemoryRouter>传递给initialEntries属性,测试工作正常。

also slideshowp2 answer is very useful if you are interested如果您有兴趣, slideshowp2 答案也非常有用

From the Checking location in tests doc:测试文档中的检查位置

  1. You can also use BrowserRouter if your test environment has the browser globals window.location and window.history (which is the default in Jest through JSDOM, but you cannot reset the history between tests).如果您的测试环境具有浏览器全局变量window.locationwindow.history (这是 Jest through JSDOM 中的默认设置,但您无法重置测试之间的历史记录),您也可以使用 BrowserRouter。
  1. Instead of passing a custom route to MemoryRouter, you can use the base Router with a history prop from the history package除了将自定义路由传递给 MemoryRouter,您还可以使用带有历史记录 package 的历史道具的基本路由器

Eg例如

index.tsx : index.tsx

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

export function SideBar() {
  return (
    <ul>
      <li>
        <Link to="/location1">location 1</Link>
      </li>
      <li>
        <Link to="/location2">location 2</Link>
      </li>
    </ul>
  );
}

index.test.tsx : index.test.tsx

import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { createMemoryHistory } from 'history';
import { SideBar } from './';
import { Router } from 'react-router';

const createRouterWrapper = (history): React.ComponentType => ({ children }) => (
  <Router history={history}>{children}</Router>
);

describe('SideBar', () => {
  it('navigation to location 1', () => {
    const history = createMemoryHistory();
    render(<SideBar />, { wrapper: createRouterWrapper(history) });
    fireEvent.click(screen.getByText('location 1'));
    expect(history.location.pathname).toBe('/location1');
  });

  it('navigation to location 2', () => {
    const history = createMemoryHistory();
    render(<SideBar />, { wrapper: createRouterWrapper(history) });
    fireEvent.click(screen.getByText('location 2'));
    expect(history.location.pathname).toBe('/location2');
  });
});

Test result:测试结果:

 PASS  stackoverflow/70974339/index.test.tsx (8.701 s)
  SideBar
    ✓ navigation to location 1 (40 ms)
    ✓ navigation to location 2 (4 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.232 s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM