AG Grid TypeScript 内联单元格编辑测试玩笑

发布于 2025-01-11 00:18:31 字数 4308 浏览 0 评论 0原文

我正在尝试创建玩笑测试,以测试我的 ag-grid 表的功能。

我目前正在进行测试,以期待网格中的默认数据,并测试向网格添加额外行数据的按钮的功能。

我正在尝试通过模拟双击我想要编辑的单元格来使用内联编辑来编辑我的一个单元格。然后是 userEvent.type。然而,单元格似乎永远不会更新。我不确定这是否是因为异步行为导致数据尚未更新,或者模拟输入/单击是否不起作用。

这是我的测试失败了:

test("tests the inline cell editing", async () => {
        const onClick = jest.fn();
        render(<DummyGrid onClick={onClick} />);

        const row = screen
            .getAllByRole("row")
            .filter((item) => item.getAttribute("row-id") === "1");
        fireEvent.doubleClick(row[1]);

        userEvent.type(row[1], "GT{enter}");

        await waitFor(() => {
            expect(screen.getByText("GT")).toBeInTheDocument();
        });
    });

以下是 DummyGrid ag-grid 组件:

import React, { useState } from "react";
import { AgGridReact } from "ag-grid-react/lib/agGridReact";
import { ColDef, ValueSetterParams } from "ag-grid-community";

import GridButton from "./GridButton";
import Car from "./car";
import { Button } from "react-bootstrap";

import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine-dark.css";

const initialState: Array<Car> = [
    { id: "0", make: "Toyota", modelName: "Celica", price: 35000 },
    { id: "1", make: "Ford", modelName: "Mondeo", price: 32000 },
    { id: "2", make: "Porsche", modelName: "Boxter", price: 70000 },
];

const fieldName = (name: keyof Car) => name;

function getRowNodeId(data: Car) {
    return data.id;
}

function onGridReady(params: object) {
    // console.log(params);
}

function onRowDataChanged(data: object) {
    // console.log(data);
}

const columnDefs: ColDef[] = [
    {
        headerName: "Make",
        field: fieldName("make"),
        editable: true,
    },
    {
        headerName: "Model",
        field: fieldName("modelName"),
        editable: true,
        // valueSetter: (params: ValueSetterParams) => {
        //     onRowDataChanged(params);
        // },
    },
    {
        headerName: "Price",
        field: fieldName("price"),
        editable: true,
    },
    {
        field: "Button",
        cellRenderer: "gridButton",
        cellRendererParams: {
            onClicked: function (
                id: string,
                make: string,
                modelName: string,
                price: number
            ) {
                // console.log(id, make, modelName, price);
            },
        },
    },
];

const gridOptions = {
    immutableData: true,
    suppressScrollOnNewData: true,
    columnDefs: columnDefs,
    frameworkComponents: {
        gridButton: GridButton,
    },
};

interface Props {
    onClick: () => void;
}
const DummyGrid: React.FC<Props> = ({ onClick }) => {
    const [rowData, setRowData] = useState(initialState);

    function addData() {
        console.log("test");
        const newRow: Car = {
            id: "3",
            make: "Land Rover",
            modelName: "Defender",
            price: 40000,
        };
        // console.log(rowData);
        setRowData((oldData) => [...oldData, newRow]);
        onClick();
    }

    return (
        <div>
            <Button data-testid="myButton" onClick={addData}>
                Add New Value
            </Button>
            <div
                className="ag-theme-alpine-dark"
                style={{ height: "300px", width: "802px" }}
            >
                <AgGridReact
                    columnDefs={columnDefs}
                    defaultColDef={{
                        sortable: true,
                    }}
                    rowData={rowData}
                    gridOptions={gridOptions}
                    onGridReady={onGridReady}
                    onRowDataChanged={onRowDataChanged}
                    getRowNodeId={getRowNodeId}
                    suppressColumnVirtualisation={true}
                ></AgGridReact>
            </div>
        </div>
    );
};

export default DummyGrid;

任何帮助或建议将不胜感激。我进行了研究,发现使用玩笑测试 ag-grid 的帮助非常小,并且没有使用玩笑测试内联 ag-grid 编辑的帮助,仅测试更新网格内容的单独按钮。

I'm trying to create jest tests in order to test the functionality of my ag-grid table.

I currently have tests for expecting the default data in the grid, and testing the functionality of a button which adds an extra row of data to the grid.

I'm trying to edit one of my cells using in-line editing by simulating a double click on the cell I want to be edited. Then followed by a userEvent.type. However the cell never seems to update. I'm not sure if this is because the data hasn't been updated yet due to the asynchronous behaviour or if the simulated typing/click isn't working.

This is my test which is failing:

test("tests the inline cell editing", async () => {
        const onClick = jest.fn();
        render(<DummyGrid onClick={onClick} />);

        const row = screen
            .getAllByRole("row")
            .filter((item) => item.getAttribute("row-id") === "1");
        fireEvent.doubleClick(row[1]);

        userEvent.type(row[1], "GT{enter}");

        await waitFor(() => {
            expect(screen.getByText("GT")).toBeInTheDocument();
        });
    });

And the following is the DummyGrid ag-grid component:

import React, { useState } from "react";
import { AgGridReact } from "ag-grid-react/lib/agGridReact";
import { ColDef, ValueSetterParams } from "ag-grid-community";

import GridButton from "./GridButton";
import Car from "./car";
import { Button } from "react-bootstrap";

import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine-dark.css";

const initialState: Array<Car> = [
    { id: "0", make: "Toyota", modelName: "Celica", price: 35000 },
    { id: "1", make: "Ford", modelName: "Mondeo", price: 32000 },
    { id: "2", make: "Porsche", modelName: "Boxter", price: 70000 },
];

const fieldName = (name: keyof Car) => name;

function getRowNodeId(data: Car) {
    return data.id;
}

function onGridReady(params: object) {
    // console.log(params);
}

function onRowDataChanged(data: object) {
    // console.log(data);
}

const columnDefs: ColDef[] = [
    {
        headerName: "Make",
        field: fieldName("make"),
        editable: true,
    },
    {
        headerName: "Model",
        field: fieldName("modelName"),
        editable: true,
        // valueSetter: (params: ValueSetterParams) => {
        //     onRowDataChanged(params);
        // },
    },
    {
        headerName: "Price",
        field: fieldName("price"),
        editable: true,
    },
    {
        field: "Button",
        cellRenderer: "gridButton",
        cellRendererParams: {
            onClicked: function (
                id: string,
                make: string,
                modelName: string,
                price: number
            ) {
                // console.log(id, make, modelName, price);
            },
        },
    },
];

const gridOptions = {
    immutableData: true,
    suppressScrollOnNewData: true,
    columnDefs: columnDefs,
    frameworkComponents: {
        gridButton: GridButton,
    },
};

interface Props {
    onClick: () => void;
}
const DummyGrid: React.FC<Props> = ({ onClick }) => {
    const [rowData, setRowData] = useState(initialState);

    function addData() {
        console.log("test");
        const newRow: Car = {
            id: "3",
            make: "Land Rover",
            modelName: "Defender",
            price: 40000,
        };
        // console.log(rowData);
        setRowData((oldData) => [...oldData, newRow]);
        onClick();
    }

    return (
        <div>
            <Button data-testid="myButton" onClick={addData}>
                Add New Value
            </Button>
            <div
                className="ag-theme-alpine-dark"
                style={{ height: "300px", width: "802px" }}
            >
                <AgGridReact
                    columnDefs={columnDefs}
                    defaultColDef={{
                        sortable: true,
                    }}
                    rowData={rowData}
                    gridOptions={gridOptions}
                    onGridReady={onGridReady}
                    onRowDataChanged={onRowDataChanged}
                    getRowNodeId={getRowNodeId}
                    suppressColumnVirtualisation={true}
                ></AgGridReact>
            </div>
        </div>
    );
};

export default DummyGrid;

Any help or advice would be much appreciated. I have researched and found a very small amount of help on testing ag-grid with jest, and nothing on testing in-line ag-grid editing with jest, only the testing of separate buttons which update the grid content.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

宫墨修音 2025-01-18 00:18:31

为了使这项工作正常进行,请尝试使用 userEvent.keyboard 函数来更新输入,而不是 userEvent.type

考虑到以下设置,此测试代码对我有用。这是使用 AG Grid v31 和 @testing-library v14。

const App = () => {
    const gridRef = useRef<AgGridReact<RowData>>(null);

    const [rowData] = useState<RowData[]>([
        { make: 'Toyota', model: 'Celica', price: 35000 },
        { make: 'Ford', model: 'Mondeo', price: 32000 },
        { make: 'Porsche', model: 'Boxster', price: 72000 }
    ]);
    const [colDefs, setColDefs] = useState<ColDef<RowData>[]>([
        { field: 'make' },
        { field: 'model' },
        { field: 'price', editable: true},
    ]);

    return (
        <div className="ag-theme-quartz" style={{ height: 400, width: 600 }}>
            <AgGridReact<RowData>
                ref={gridRef}
                rowData={rowData}
                columnDefs={colDefs}
                modules={[ClientSideRowModelModule]} />
        </div>
    );
};

    test('double click cell to edit', async () => {
        render(<App />);

        let porschePrice = await screen.findByText('72000')

        // double click to enter edit mode       
        await userEvent.dblClick(porschePrice);

        let input: HTMLInputElement = within(porschePrice).getByLabelText('Input Editor');

        await userEvent.keyboard('100000');

        // press enter to save
        fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });

        porschePrice = await screen.findByText('100000')

    });

To make this work try to use userEvent.keyboard function to update the input instead of userEvent.type

This test code is working for me given the following setup. This is using AG Grid v31, and v14 of @testing-library.

const App = () => {
    const gridRef = useRef<AgGridReact<RowData>>(null);

    const [rowData] = useState<RowData[]>([
        { make: 'Toyota', model: 'Celica', price: 35000 },
        { make: 'Ford', model: 'Mondeo', price: 32000 },
        { make: 'Porsche', model: 'Boxster', price: 72000 }
    ]);
    const [colDefs, setColDefs] = useState<ColDef<RowData>[]>([
        { field: 'make' },
        { field: 'model' },
        { field: 'price', editable: true},
    ]);

    return (
        <div className="ag-theme-quartz" style={{ height: 400, width: 600 }}>
            <AgGridReact<RowData>
                ref={gridRef}
                rowData={rowData}
                columnDefs={colDefs}
                modules={[ClientSideRowModelModule]} />
        </div>
    );
};

    test('double click cell to edit', async () => {
        render(<App />);

        let porschePrice = await screen.findByText('72000')

        // double click to enter edit mode       
        await userEvent.dblClick(porschePrice);

        let input: HTMLInputElement = within(porschePrice).getByLabelText('Input Editor');

        await userEvent.keyboard('100000');

        // press enter to save
        fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });

        porschePrice = await screen.findByText('100000')

    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文