Mock a middleware function using jest

Viewed 22

This is my middleware,

export const parseUser = (req, res, next) => {
    const token_header = req.header('Authorization');
    if (token_header) {
        req.user = jwt_decode(token_header.split(' ')[1].split(' ')[0]);
        req.token = token_header.split(' ')[1].split(' ')[0];
        next();
    } else {
        next();
    }
};

this is my router,

router.get('/get/', parseUser, swaggerValidation.validate,
    async(req, res) => {
            ...
        } catch (err){
            ...
        }
    });

i am trying to mock the parseUser function and assign req.user and req.token values using jest and pass it, i need those values to authorize user and need the value assigned to do database query, I am using jest to mock the functions, I have tried google and stackoverflow, i was not able to solve it with those example, i have tried below methods and others,

jest.mock('../../utils/permission');
const mockedParseUser = jest.mocked(parseUser, true)

mockedParseUser.mockReturnValueOnce({req.user: "value", req.token: "value");

i have also tried,

const return = {req.user: "value", req.token: "value"}
const mockedReturn = jest.fn((): any => return}
jest.spyOn('../../utils/permission', parseUser).mockImpementation((): any => mockReturn())

Nothing worked for me, can someone help me with mocking the parseUser().

0 Answers
Related