reactjs 如何测试条件渲染提供了一个方法,返回布尔值?

tyu7yeag  于 2023-08-04  发布在  React
关注(0)|答案(1)|浏览(92)

我想测试一个条件呈现,但是我在从自定义钩子获取函数(userHasAccess)并模拟返回true时遇到了麻烦,因此元素被呈现在屏幕上。

useData.tsx

import React from 'react';

const useData = () => {

  function userHasAccess(access: 'student' | 'teacher' | 'admin'): boolean {
    return getLoggedUser()?.access === access
  }

  others functions...

  return {
    userHasAccess,
    others functions...
  }
}

export default useData;

字符串

侧边栏.tsx

const Sidebar = () => {
  const { userHasAccess } = useData();

  return (
      <ul>
        {userHasAccess('admin') && <li><Link to='usuarios'>Users</Link></li>}
      </ul>
    </nav>
  )
}

export default Sidebar;

Sidebar.test.tsx

it('should render correctly for admin', () => {
    render(<BrowserRouter><Sidebar /></BrowserRouter>)

    expect(screen.getByText("Users")).toBeInTheDocument();

  })
})


在这种情况下,我如何进行测试,以便:
public void println();
通过测试?

kknvjkwl

kknvjkwl1#

据我所知,你只需要mock userHasAccess来返回true
试试下面的代码:

// Sidebar.test.tsx

import React from 'react';
import { render, screen } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import Sidebar from './Sidebar'; 
import useData from './useData';

jest.mock('./useData');

describe('Sidebar', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should render correctly for admin', () => {
    useData.mockReturnValue({ userHasAccess: jest.fn().mockReturnValue(true) });

    render(
      <BrowserRouter>
        <Sidebar />
      </BrowserRouter>
    );

    expect(screen.getByText('Users')).toBeInTheDocument();
  });
});

字符串

相关问题