Home > Blockchain >  How to mock Json.stringify in jest test cases?
How to mock Json.stringify in jest test cases?

Time:08-30

try {
            myObject = {
                a: JSON.stringify(obj)
            };
        } catch (err) {
            logError(`myMethod :::: ${err.message}`);
        }

I wanted to cover catch block under jest testcases but I am new to this jest test cases so I m not getting how to mock Json.stringify and how to throw error?

I am mocking as below. But I am getting error as: TypeError: Invalid JSON Can u please tell me where I am going wrong?

JSON.stringify = jest.fn().mockImplementationOnce(() => { throw new TypeError('Invalid JSON'); });

CodePudding user response:

if you pass an invalid object inside the JSON.stringify your code should throw the error and go to the catch block.

CodePudding user response:

As I understand it, you want to test the catch part of your code. You can pass an invalid Json as an object.

So, if your function is:

function jestTest(obj) {
   try {
       myObject = {
           a: JSON.stringify(obj)
       };
   } catch (err) {
        logError(`myMethod :::: ${err.message}`);
   }
}
module.export = jestTest

then, in your test function, you can use this:

var jestTestObject = require('./jestTest') // this hold your exported module, code which you are testing
JSON.stringify = jest.fn(); // do not mock to return "Invalid Json"
test("CatchPart", () => {
    var invalidJson = ({ "a": 1}) // Create invalid json
    var logErrorSpy = jest.spyOn(jestTestObject, 'logError') // spy on logError
    jestTest(obj); // Invalid object will take it to catch part
    expect(logErrorSpy).toHaveBeenCalledTimes(1) // which will call logError once
})
  • Related