1 year ago

#247066

test-img

Durgaraj Karki

Unit testing route handler with Jest?

I have the following code snippet that works as a handler for my certain route. I am trying to perform the unit test using Jest but I have no idea what are things I can test on the following function. I managed to test something but I am not sure whether I am in the right direction or not and what to test.

route.js

exports.routeHandler = function (param1, param2) {
  return async function(req, res){
    const { id } = req.params;
    try {
      const user = await param1.user.getAuthUser(res);
      if(!user) return res.sendStatus(404).json();
      const results = await getUserId(user, param1, param2);
      const getInformation = await getInfo(results, id, param1, param2);
      res.sendStatus(200).json({
        getInformation
      })
    } catch (error) {
      return res.sendStatus(500);
    }
  }
}

route.test.js

const mockResponse = () => {
  const res = {};
  res.sendStatus = jest.fn().mockReturnValue(res);
  res.json = jest.fn().mockReturnValue(res);
  return res;
}

const mockRequest = () => {
  return {
      params: {
          id : 1
      }
  }
}

const mockParam1 = {
  user: {
      getAuthUser: jest.fn()
  }
};
const mockParam2 = {
  error: jest.fn()
};


describe('checkAuth', () => {
  test('should 404 if user is not set', async() => {
      const req = mockRequest();
      const res = mockResponse();
      const routeHandlerTest = routeHandler(mockParam1, mockParam2);
      await routeHandlerTest(req, res)
       expect(res.sendStatus).toHaveBeenCalledWith(404);
  })
})

Another problem here is I am not being able to mock or spy the function getUserId and getInfo.

getUserId.js

async function getUserId(user, param1, param2) {
  try {
    return await param1.database.query(
      'SELECT "id" from "user" WHERE "username" = $username',
      {
        type: "SELECT",
        bind: { username: user.username },
      }
    );
  } catch (error) {
    param2.error(error);
  }
}

getInfo.js

async function getInfo(results, id, param1, param2) {
  try {
    return await param1.database.query(
      // query
      ,
      {
        type: "SELECT",
        bind: {
          id: id,
          userId: results[0].id,
        },
      }
    );
  } catch (error) {
    param2.error(error);
  }
}

Note: the functions getUserId and getInfo are in different modules

javascript

unit-testing

jestjs

mocking

spy

0 Answers

Your Answer

Accepted video resources