0

I am trying to test the following onColumnToggle function, which is used to toggle some columns in a table (using Primereact Column Toggler):

       constructor() {
            super();
            this.state = {
                selectedColumns: []
            }
        }

       componentDidMount() {
        this.setState({
            selectedColumns: this.props.columnProps,
          })
        }

        onColumnToggle(event) {
        let selectedColumns = event.value;

        let orderedSelectedColumns = this.props.columnProps.filter(obj => selectedColumns.includes(obj));

        this.setState({selectedColumns: orderedSelectedColumns});
    }

The function in my application is working fine and the toggling works like in the documentation. I am having some difficulties testing the method. At the moment I have the following:

    describe('MyComponent', () => {
    let wrapper;
    let instance;
    beforeEach(() => {
        MyComponent.defaultProps = {
            columns: [
                {field: 'vin', header: 'Vin'},
                {field: 'year', header: 'Year'},
                {field: 'brand', header: 'Brand'},
                {field: 'color', header: 'Color'}
            ]
        };

        wrapper = shallow(<MyComponent columnProps={MyComponent.defaultProps.columns}/>);
        instance = wrapper.instance();
        jest.clearAllMocks();
    });

    describe('onColumnToggle function', () => {
        it('should change "selectedColumns" state', () => {
            const columnMock = {
                 value: [
                   {field: 'year', header: 'Year'},
                   {field: 'brand', header: 'Brand'}
                ]
             }
            instance.onColumnToggle(columnMock);
            expect(wrapper.state('selectedColumns')).toEqual(columnMock.value)
        })
    })

I expect that my selectedColumns state becomes equal to my columnMock value. Instead, I get the following error:

    Error: expect(received).toEqual(expected) // deep equality

- Expected
+ Received

- Array [
-   Object {
-     "field": "year",
-     "header": "Year",
-   },
-   Object {
-     "field": "brand",
-     "header": "Brand",
-   },
- ]
+ Array []

Debugging the issue shows that the filtering part of onColumnToggle function doesn't filter out the common values from the two arrays and orderedSelectedColumns gives back an empty array. If I console log selectedColumns.includes(obj) then it evaluates to false every time. What am I doing wrong? The function works as expected in my application.

User3000
  • 65
  • 1
  • 12

1 Answers1

1

Array.includes compares by reference so it will return false also for 2 variables having same key/values but not being the same object. In your case, I would filter by explicitly comparing the properties of your objects:

let orderedSelectedColumns = columnProps.filter(obj => selectedColumns.some(b => b.field === obj.field && b.header === obj.header));
Dario
  • 6,152
  • 9
  • 39
  • 50