Testing Ag-Grid React’s Custom Cell Renderer Component

I am on a journey to acquire the necessary skills for testing software. I will document the techniques and tricks I learned via blog posts.

Subject under test(sut):

a generic cell renderer component for Ag-Grid React renders any given component of type FC<ICellRendererParams>.

Behaviour

The component being rendered is a small button that uses formatted cell value or cell value as its text. When the user clicks the button, it calls the specified action.

Code

Notes

  1. the test shows how to use the cell renderer in a TestComponent, which is sweet, one of the benefits of testing

  2. the test must use the async query findByText instead of getByText. findByText will continuously try to search for the DOM until it finds the element or timeout. getByText doesn’t work (button not found error) here because the way Ag-Grid renders its cell renderers.

  3. use userEvent to mimic the user’s click action, which emits a host of events, same as it happens when a user clicks the button in the browser.

  4. the action is a spy to get asserted because this is the expected behaviour of the sut. I did not directly assert the other expected behaviour, rendering the button with value as its text. But it is tested because the button is used to trigger the event in the test.

  5. no mocks. The test is rendering the AgGridReact component and the Button component from @mui/material

Side Notes

The beauty about React is that it embraces functional programming. Its building block is function and encourages the use of pure function. So we can compose simple and pure functions together to make powerful yet simple, elegant and easy to test components.

In this instance, I used a generic cell renderer component to bridge between Ag-Grid’s API and my button component. The useSmallButton hook takes an function and returns a component that uses input. With this generic cell renderer component, I can render anything in a cell. I think Ag-Grid could implement such a generic component to make its API easier to use if not already.

My favourite feature of JavaScript is the spread/rest operator. With this operator, the props of a functional React component is like a contract, an interface, really elegant and powerful.

16