how to mock json.parse() in jest tests

Viewed 11496

I have a try/catch in my code and when the code falls into the catch part it hits a JSON.parse()

catch(err){
    JSON.parse(err.message)
}

the code is working but the tests are failing. the test is just asserting something is happening in the try

try {
   popUp.method(mockedUrl)
}

the test is just asserting that this method was called but it's failing because something is blowing up in the JSON.parse() stage. just wondering how I can stub this out so that it knows what I've passed into the json?

1 Answers

You could mock the JSON.parse implementation

JSON.parse = jest.fn().mockImplementationOnce(() => {
  // return your what your code is returning.
});

This should be enough once you shouldn't test the javascript built-in object: JSON. so you return what your code is expecting from it and the rest should be fine.

Related