Future proof by checking for existence before binding functionality

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dependencies category.

Last Updated: 2024-11-21

In my tests I wanted to mock window.matchMedia which was not available in jsdom. My first inclination was to do:

window.matchMedia =
  jest.fn().mockImplementation(query => {
    return {
      addListener: jest.fn(),
      removeListener: jest.fn()
    }
  })

This is suboptimal, since it overrides window.matchMedia even when the function is actually defined in the jsdom library (which help with testing)

Also, if a mistake accidentally caused the previous code to be pushed to production, we'd break things.

Therefore this pre-check for existence prior to mocking is preferred:

window.matchMedia = window.matchMedia ||
  jest.fn().mockImplementation(query => {
    return {
      addListener: jest.fn(),
      removeListener: jest.fn()
    }
  })