Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in Jest test req.session.save is not a function

It giving me a error at await req.session.save(); like req.session.save is not a function.

How I can create mock for req.session.save()?

myController.ts

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

static async connect(req: any, res: Response) {
    ...
    req.session.testToken = {
        refresh_token: refresh_token,
        access_token: access_token,
        expires_in: 1200
    };
    await req.session.save();

    res.json({success:true, message:'Connected'});
}

myController.spec.ts

descibe('test',()=> {
    let req = httpMocks.createRequest();
    let res = httpMocks.createResponse();

    it('should connected',()=> {
        myController.connect(req,res);

        expect(res.statusCode).toBe(200);
        expect(res._isEndCalled()).toBeTruthy();
    });
})

>Solution :

In the context of that particular test, you are not making any assertion on the req object, so you can just use a simple object literal.

let req = {
  session: {
    save: () => Promise.resolve()
  },
};

In case you will need to assert that the req.session.save was called, you can create a mock function with Jest in this way

let req = {
  session: {
    save: jest.fn().mockResolvedValue(undefined)
  },
};

EDIT
I see your connect method is async, but your test is not structured to handle it asynchronously. You should use one of the methodologies explained > here <

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading