Jest testing with URL object

Viewed 4307

I am have a case where my code is using the URL api, created as such:

const _url = new URL(window.location.href);

and used like so:

if (_url.searchParams.get('locale')) {
    do something
}

However in my jest tests I get an error:

TypeError: Cannot read property 'get' of undefined

I have tried globally mocking by doing this in my setup file:

global.URL = jest.fn(() => {
  return {
    searchParams: jest.fn(() => {
      return {
        get: jest.fn(() => {
          return '';
        }),
      };
    }),
  };
});

But it doesn't seem to work. Looking at the console logged output of my _url object, it looks like it is missing the searchParam property all together:

URL {
  [Symbol(impl)]: URLImpl {
    _url: {
      scheme: 'http',
      username: '',
      password: '',
      host: 'localhost',
      port: null,
      path: [Array],
      query: null,
      fragment: null,
      cannotBeABaseURL: false
    },
    [Symbol(wrapper)]: [Circular]
  }
}

What am I doing wrong here?

2 Answers

I was able to solve it by doing a global mock in the set up file as so:

global.URL = (() => {
  return {
    searchParams: {
      get: jest.fn((param) => {
        const reg = `[?&]${param}=([^&]*)`;
        return (window.location.search.match(reg) && window.location.search.match(reg)[1]) ? window.location.search.match(reg)[1] : '';
      }),
    },
  };
});

To avoid unit test errors, you can use try {} catch(e) {} block with default value like this:

    const myFunction = url => {
        try {
            return new URL(url).hostname;
        } catch (e) {
            console.warn('new URL(...) object is not supported');
        }
        return {};
    }
Related