简体   繁体   中英

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);
});

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))

I found good way to test if array is sorted properly.

Just use:

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

When sorting function is not set, default sorting order is ascending.

You can read more about sorting here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM