简体   繁体   English

我如何断言哪个值已传递给<li>与 jest 和 testing-library/react 反应的关键属性

[英]How can I assert which value has been passed to a <li> key attribute in react with jest and testing-library/react

I'm using react+ts and jest+testing-library for testing.我正在使用 react+ts 和 jest+testing-library 进行测试。 I want to unit test the following code and would like to make sure that the person.id is set as the key attribute of the li element.我想对以下代码进行单元测试,并希望确保将person.id设置为li元素的key属性。 Initially I thought I could assert it by running expect(listItems[1]).toHaveAttribute('key', '2');最初我以为我可以通过运行expect(listItems[1]).toHaveAttribute('key', '2');来断言它expect(listItems[1]).toHaveAttribute('key', '2'); but it seems that the key attribute is removed from the final HTML, which is what I seem to be testing.但似乎 key 属性已从最终的 HTML 中删除,这似乎是我正在测试的内容。 How can I make sure that the person.id is passed to the key attribute of the list item?如何确保将 person.id 传递给列表项的 key 属性?

import React from 'react';
import Api from '../control/api';

const PersonList = () => {
    const persons = Api.getPersons();

    return (
        <ul>
            {persons.map((person) => {
                return (
                    <li key={person.id}>
                        {`${person.id}: ${person.name.familyName}, ${person.name.givenName}`}
                    </li>
                );
            })}
        </ul>
    );
};

export default PersonList;

The test:考试:

import React from 'react';
import { render, screen } from '@testing-library/react';
import PersonList from '../../components/PersonList';
import { getPersons } from '../../control/api';

jest.mock('../../control/api');

const mockGetPersons = getPersons as jest.MockedFunction<typeof getPersons>;

describe('The PersonList component', () => {
    it('should output empty list if there are no persons returned by the api', () => {
        mockGetPersons.mockReturnValue([]);

        render(<PersonList />);

        const lists = screen.getAllByRole('list');
        expect(lists).toHaveLength(1);
    });

    it('should render one person returned by api', () => {
        mockGetPersons.mockReturnValue([
            {
                id: '1',
                name: {
                    familyName: 'Duck',
                    givenName: 'Donald',
                },
            },
        ]);

        render(<PersonList />);

        const listItems = screen.getAllByRole('listitem');
        expect(listItems).toHaveLength(1);
        expect(listItems[0]).toHaveTextContent('1: Duck, Donald');
    });

    it('should render several persons returned by api', () => {
        mockGetPersons.mockReturnValue([
            {
                id: '1',
                name: {
                    familyName: 'Duck',
                    givenName: 'Donald',
                },
            },
            {
                id: '2',
                name: {
                    familyName: 'Duck',
                    givenName: 'Dagobert',
                },
            },
            {
                id: '3',
                name: {
                    familyName: 'Mouse',
                    givenName: 'Mickey',
                },
            },
        ]);

        render(<PersonList />);

        const listItems = screen.getAllByRole('listitem');
        expect(listItems).toHaveLength(3);
        expect(listItems[0]).toHaveTextContent('1: Duck, Donald');
        // expect(listItems[1]).toHaveAttribute('key', '2');
        expect(listItems[2]).toHaveTextContent('3: Mouse, Mickey');
    });
});

The key property is used internally by react and it does not matter what it is set to, as long as the value is unique for each item in the current list. key 属性由 react 在内部使用,它被设置为什么并不重要,只要当前列表中的每个项目的值都是唯一的。 Therefore none of the users of the code (neither end-user or developer) will use/see/know about the value set there, which means that we should not write tests to assert the key property.因此,代码的用户(最终用户或开发人员)都不会使用/查看/知道那里设置的值,这意味着我们不应该编写测试来断言 key 属性。

More about the key property in the react docs有关react 文档中关键属性的更多信息

Blog article about Testing Implementation Details关于测试实施细节的博客文章

Stackoverflow question about Accessing the key property programmatically关于编程方式访问关键属性的Stackoverflow 问题

暂无
暂无

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

相关问题 如何使用 jest 和(react-)testing-library 测试浏览器后退按钮的行为? - how can i test browser back-button behaviour using jest and (react-) testing-library? 如何使用 jest、react、testing-library 为这个组件编写单元测试? - How can I write a unit test using jest, react, testing-library for this component? 我如何测试 useState 钩子是否被 jest 和 react 测试库调用? - how can I test if useState hook has been called with jest and react testing library? 如何在 jest 和 @testing-library/react 中测试 catch 部分 - How to test catch part in jest and @testing-library/react 使用 testing-library 和 jest 的 React 组件抛出的测试错误 - Testing error thrown by a React component using testing-library and jest 如何使用@testing-library/user-event 版本 14 在 React 中测试 `onKeyDown` 道具? - How can I test `onKeyDown` prop in React with @testing-library/user-event version 14? 如何在 jest 和 testing-library/react-native 中获取整个组件树? - How to get the whole components tree in jest and testing-library/react-native? React testing-library 模拟触摸和移动,指针的键是什么? - React testing-library to simulate touch and move, what is the key for a pointer? 无法使用 Jest 和 Testing-Library 测试 React 组件渲染,因为 Jest 没有可用的文档 - Trouble testing React component render with Jest and Testing-Library because there's no Document available to Jest 使用 Jest 和 @testing-library/react-hooks 在 TypeScript 中单元测试自定义 React Hook - Unit Testing Custom React Hooks in TypeScript using Jest and @testing-library/react-hooks
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM