Home > database >  How do I unit test a filter function in React Native?
How do I unit test a filter function in React Native?

Time:01-22

I'm building a live music gig listing app in React Native with expo.

An array of gig objects is fetched from firebase, with the following shape:

gigs:
[
  {
    dateAndTime:{seconds:2345234748},
    gigName: 'gigAtVenue',
    ...
  },
  {...}
]

In my component listByDay.txs, I've written some code to filter through this array of gig objects, and return only the current day's gigs:

 const gigsToday = gigs.filter((gig) => { 
    const formattedDate = format(new Date(currentDateMs), 'do MMMM Y')
    const formattedGigDate = format(new Date(gig.dateAndTime.seconds*1000) ,'do MMMM Y')
    return formattedGigDate === formattedDate
  })

I've written the following test, but it seems very clunky to be re-writing the filter function for my test - is there a way I can "extract" the filter from it's component listByDay.tsx? What's the best library to use for a test like this?

    test('should filter gigs by date', () => {
      // create an array of gigs
      const gigs = [
        { dateAndTime: { seconds: 1609459200 } }, // 1 September 2021
        { dateAndTime: { seconds: 1609545600 } }, // 2 September 2021
        { dateAndTime: { seconds: 1609632000 } }, // 3 September 2021
      ]
  
      // create a new date object with the current date
      const currentDate = new Date(2021, 8, 1) // 1 September 2021
  
      // pass the gigs and currentDate to the filter function
      const gigsToday = gigs.filter((gig) => { 
        const formattedDate = format(currentDate, 'do MMMM Y')
        const formattedGigDate = format(new Date(gig.dateAndTime.seconds*1000) ,'do MMMM Y')
        return formattedGigDate === formattedDate
      })
  
      // check that the filter function returned the correct gigs
      expect(gigsToday).toBe([{ dateAndTime: { seconds: 1609459200 } }])
    })

CodePudding user response:

You can create a standalone callback function to be used by the first parameter of Array.filter.

Remove the callback function from the react component body, then you can export the function to be unit tested it by itself.

const gigs = [{
  dateAndTime: {
    seconds: 2345234748
  },
  gigName: 'gigAtVenue',
}]

export const filterByToday = (gig) => {
  const formattedDate = format(new Date(currentDateMs), 'do MMMM Y')
  const formattedGigDate = format(new Date(gig.dateAndTime.seconds * 1000), 'do MMMM Y')
  return formattedGigDate === formattedDate
}


const ListByDay = ({ gigs }) => {
  const gigsToday = gigs.filter(filterByToday)

  return (
    // some JSX
  )
}

Edit eager-williams-80op2g

  • Related