Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock json.parse() in jest tests

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?

like image 949
the venom Avatar asked Nov 09 '18 15:11

the venom


People also ask

How to mock JSON parse in jest?

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

How do you mock a JSON object in jest?

You can either use moduleNameMapper in your jest settings to point the import to an mocked json file. Or you can use jest. mock inside your test to mock the file directly, note that you have to add the { virtual: true } parameter.

What is JSONPath parse?

JSONPath is an expression language to parse JSON data. It's very similar to the XPath expression language to parse XML data. The idea is to parse the JSON data and get the value you want. This is more memory efficient because we don't need to read the complete JSON data.

Is JSON Parsable Javascript?

Parsing FunctionsFunctions are not allowed in JSON. If you need to include a function, write it as a string.


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.

like image 96
sergioviniciuss Avatar answered Sep 19 '22 17:09

sergioviniciuss