4

有谁知道如何用 Jest/Enzyme 测试 AgGridReact?我试图模拟应该自动调用的 onGridReady 回调,但它似乎没有被触发。这是我的测试的简化版本:

import React from "react";
import { mount} from "enzyme";

const AgGridReact =
  typeof window === "undefined"
    ? () => null
    : require("ag-grid-react").AgGridReact;

var spy = jest.fn();

// Grid.prototype.onGridReady = spy;
var columnDefs = [
  { headerName: "Make", field: "make" },
  { headerName: "Model", field: "model" },
  { headerName: "Price", field: "price" }
];

// specify the data
var rowData = [
  { make: "Toyota", model: "Celica", price: 35000 },
  { make: "Ford", model: "Mondeo", price: 32000 },
  { make: "Porsche", model: "Boxter", price: 72000 }
];

// let the grid know which columns and what data to use
var gridOptions = {
  columnDefs: columnDefs,
  rowData: rowData,
  onGridReady: spy
};

mount(<AgGridReact id="myGrid" {...gridOptions} />);

expect(spy).toHaveBeenCalledTimes(1);

任何想法/建议将不胜感激。谢谢!

4

2 回答 2

2

而不是 mount 你应该使用浅。酶浅方法将公开所有自定义事件,您可以轻松模拟它们。

    //AgGridReact is wrapped inside Grid component
    const wrapper = shallow(<Grid/>)

    const agGridReact = wrapper.find(AgGridReact)

    agGridReact.simulate('gridReady')
于 2018-03-31T14:55:03.773 回答
2

该函数onGridReady是异步调用的,因此您无法在 mount 调用后立即检查它。取而代之的是,将其包装成一个承诺或使用doneJest 中的函数。

于 2019-03-14T13:40:57.217 回答