使用内存路由器渲染需要参数的组件的测试不起作用,"找不到角色:标题"



我正在尝试对包含userParams()调用的Profile组件进行单元测试,以从路径变量获取userID,从而以配置文件格式显示该用户的信息。

该测试使用MemoryRouter以正确的参数路由到测试,我不确定它为什么返回找不到"role"heading",因为JSX组件中有2个heading元素,默认情况下应该为其指定role"heading(。

我不确定测试配置是否正确,或者是否有其他原因。

失败:

Unable to find role="heading"
Ignored nodes: comments, <script />, <style />
<body>
<div />
</body>
Ignored nodes: comments, <script />, <style />
<html>
<head />
<body>
<div />
</body>
</html>
Error: Unable to find role="heading"
Ignored nodes: comments, <script />, <style />
<body>
<div />
</body>

Profile.test.js

import React from 'react'
// import API mocking utilities from Mock Service Worker
import {rest} from 'msw'
import {setupServer} from 'msw/node'
// import react-testing methods
import {render, fireEvent, waitFor, screen} from '@testing-library/react'
import routeData, {MemoryRouter, Route, Routes} from 'react-router';
// add custom jest matchers from jest-dom
import '@testing-library/jest-dom';
import config from "../configuration/Configuration.json";
import {Profile} from "../pages/Profile";
const userId = 1;
const server = setupServer(
rest.get(
config.URL + '/users/' + userId,
(req, res, ctx) => {
return res(ctx.json({
userId: 1,
email: 'testEmail@outlook.com',
password: null,
firstName: 'Test',
lastName: 'User'
}))
}
),
)
const renderWithRouter = ({ children }) => (
render(
<MemoryRouter initialEntries={['/users/1']}>
<Routes>
<Route path='/users/:userId'>
{children}
</Route>
</Routes>
</MemoryRouter>
)
)
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
test('loads and displays profile', async () => {
renderWithRouter(<Profile />)
await waitFor(
() => screen.getByRole("heading").toHaveTextContent("Test User")
)
})

Profile.js:

import React from 'react'
import {useEffect, useState} from "react";
import UserService from "../services/UserService";
import {getFullName} from "../util/Util";
import '../css/profile.css';
import {useParams} from "react-router-dom";
export const Profile = () => { 
//array of compatible users fetched for a user.
const [userProfileInformation, setUserProfileInformation] = useState([]);
const [isLoading, setLoading] = useState(true);
const { userId } = useParams();
useEffect(() => {
getUserProfileInformation().then(() => {
setLoading(false);
});
}, []);
const getUserProfileInformation = async () => {
const response = await UserService.getUserProfileInformation(userId)
.then(response => response.json())
.then(data => {
setUserProfileInformation(data);
});
}
if (isLoading) {
return (
<div id="loading">
<h2>Loading...</h2>
</div>
)
}
return (
<div>
<div className="profileCard">
<h1 name='fullName'>
{getFullName(
userProfileInformation.firstName, 
userProfileInformation.lastName
)}
</h1>
<h2>{userProfileInformation.email}</h2>
</div>
</div>
)
}

问题

我认为问题出在测试渲染函数renderWithRouter上。

  1. CCD_ 6正在呈现CCD_;道具";作为Route的子级,但在嵌套路由的情况下,Route的唯一有效子级是另一个Routechildren道具应该传递给Route组件的element道具
  2. renderWithRouter是一个正则函数,而不是React组件,因此它的参数不是props对象。测试正在传递<Profile />作为参数,而renderWithRouter正试图从中销毁children属性。`children是OFC未定义的

解决方案

更新renderWithRouter以使用传递给Route组件的element属性的element参数。

const renderWithRouter = (element) => (
render(
<MemoryRouter initialEntries={['/users/1']}>
<Routes>
<Route path='/users/:userId' element={element} />
</Routes>
</MemoryRouter>
)
);

最新更新