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

Time:06-21

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

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();
    });
})

CodePudding user response:

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 <

  • Related