0
jest.spyOn( URLSearchParams.prototype, 'get' ).mockReturnValue( null )

I am expecting this code to cause get to evaluate to null but this doesn't appear to be the case, Istanbul is being used and the code below does not ever evaluate to the falsey condition (shown as a failure to cover ?? '':

    const startDate: string = new URLSearchParams( queryParams ).get( 'start' ) ?? ''
    const endDate: string = new URLSearchParams( queryParams ).get( 'end' ) ?? ''

Any idea what the issue might be?

For context here is the start of the relevant component and test:

// component under test:
const EmployeeTable = () => {
    const queryParams = useLocation().search
    const { id } = useParams<{ id: string }>()
    const employeeId: number = Number( id )
    const startDate: string = new URLSearchParams( queryParams ).get( 'start' ) ?? ''
    const endDate: string = new URLSearchParams( queryParams ).get( 'end' ) ?? ''

// the jest test
    it( 'should render the employee table page section without data', () => {
        jest.spyOn( dataHooks, 'useEmployeeTimeSummaries' ).mockImplementation( (): any => ( {
            data: null,
        } ) )
        jest.spyOn( URLSearchParams.prototype, 'get' ).mockReturnValue( null )
        const { getByTestId } = render( <EmployeeTable />, { wrapper: reactQueryProvider } )
        expect( getByTestId( TEST_ID_EMPLOYEE_TABLE ) ).toBeInTheDocument()
    } )
Sean D
  • 3,810
  • 11
  • 45
  • 90
  • Why mock `URLSearchParams` at all? It's much easier, and far less coupled to the details of your implementation, to control the location: https://reactrouter.com/web/guides/testing, https://stackoverflow.com/a/65275037/3001761 – jonrsharpe Nov 02 '21 at 23:30

0 Answers0