Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking URLSeachParams

We are using jest for mocking. enzyme for rendering in our application.

Here I am trying to mock URLSearchParams's get method.

I tried to use

jest.spyOn(URLSearchParams, 'get'); 

But it's not working.

My react class looks like bellow

export default class Concepts extends React.Component {
  static getDerivedStateFromProps(props) {
  const searchParams = new URLSearchParams(props.search);
  return {
     keyword: searchParams.get('q')
   };
}

My test is looks like below

it('should be able to change the state', () => {
  jest.spyOn(URLSearchParams, 'get');
  const wrapper = mount(
        <Concepts search="test" />
   );
});

Is it correct way? are there any other ways to do it? Thanks in advance :)

like image 698
Maharjun M Avatar asked Oct 19 '18 04:10

Maharjun M


1 Answers

You have to mock get on URLSearchParams.prototype, like :

jest.spyOn(URLSearchParams.prototype, 'get').mockImplementation((key) => key);
like image 111
manuquentin Avatar answered Sep 19 '22 22:09

manuquentin