Immortal Star
Immortal Star

Reputation: 49

Unit Test case for Sorting in Jest

I am new to reactjs and jest. I am trying to write a test case that will pass the sort function written in container. I am not sure how to write it.

I am getting TypeError: Cannot read property 'sort' of undefined error when I try to run the test case.

Actual Array

let testArray=[{trackingId:'1',updated: '1512885243'},
                {trackingId:'1',updated: '1512485253'},
                {trackingId:'3',updated: '1512884233'},
                {trackingId:'2',updated: '1512885243'}];

Expected Array

let sortedArray = [{trackingId: '1', updated: '1512885243'},
                   {trackingId: '1', updated: '1512885253'},
                 {trackingId: '2', updated: '1512885243'},
                 {trackingId: '3', updated: '1512884233'}]

// I am thinking something like:
describe('Sorting', () => {
      it('Array should be sortedby trackingId', () => {
        testArray.sort((a,b) => {
          if (a.trackingId !== b.trackingId) {
            return a.trackingId - b.trackingId;
          }
          return new Date(b.updated) - new Date(a.updated);
        });
        expect(component.contains(result))
          .toEqual(expect.arrayContaining(sortedArray))

});

Sort function in my container class for which I am writing the unit test:

customerTrackingInfo = customerTrackingInfo.sort( (a,b) => {
        if (a.trackingId !== b.trackingId) {
          return a.trackingId - b.trackingId;
        }
        return new Date(b.updated) - new Date(a.updated);
});

Upvotes: 4

Views: 17825

Answers (1)

jakson dikison
jakson dikison

Reputation: 149

I like how elegant @Rafał Figura's answer is, but it has one one major flaw, which is that even though Array.prototype.sort() returns a sorted array, it sorts the original array in place, mutating it. This means that

expect(array).toStrictEqual(array.sort(sortingFunction))

will always pass since array.sort(sortingFunction) will update array to be the sorted value. The fix is simple, though. Just copy the array before sorting it:

expect(array).toStrictEqual([...array].sort(sortingFunction))

Upvotes: 7

Related Questions