1

I have this function which I hope to return the url added with the parameters

export const addParamsToURL = (
  params: param | param[],
  url?: string
): string => {
  if (!url) return ''
  const __url = new URL(url)
  const __params = new URLSearchParams(__url.search)

  if (params instanceof Array) {
    params.map(({key, value}) => __params.append(key, value))
  } else {
    __params.append(params.key, params.value)
  }

  return `${__url.origin}${__url.pathname}?${__params}`
}

I created the scenario test below and I would like to know if I should make a mock for it and what would be the best approach. Do I really need to mock? jest.fn, jest.mock? I'm still pretty new to testing

import {addParamsToURL} from '../../src/utils/addParamsToURL'


const baseURL = 'https://www.idinheiro.com.br'

const singleParam = {key: 'a', value: 'b'}

const multipleParams = [

  {key: 'a', value: 'b'},

  {key: 'c', value: 'd'},

]


describe('AddParamsToURL input a base url and params returns the full URL', () => {

  it('Should return "" if not given a url', () => {

    const res = addParamsToURL(singleParam, undefined)

    expect(res).toBe('')

  })


  it('Should return the full url if given a simple param', () => {

    const res = addParamsToURL(singleParam, baseURL)

    expect(res).toBe('https://www.idinheiro.com.br/?a=b')

  })
})
Renan Bessa
  • 429
  • 1
  • 6
  • 13

1 Answers1

1

This utility function is not related to Reactjs and react-testing-library. You don't need mock objects for testing this function. This function is pure, and your testing approach is correct.

Some common scenarios mock are useful:

  • The real object has non-deterministic behavior
  • The real object is complicated to setup
  • The real object has behavior that is hard to trigger
  • The real object is slow
  • The real object is a user interface
  • The real object uses a callback
  • The real object does not yet exist

Also see When should I mock?

Lin Du
  • 88,126
  • 95
  • 281
  • 483