Next.js Discord

Discord Forum

TypeError: (0 , _authMiddleware.handleCors) is not a function

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
hey, I am working on unit testing and API endpoint that is created using NextJS API routing
/api/auth/login
endpoint. I successfully mocked the Database connections and also the
requireUsernamePasswordLogin
middleware. However, I cannot mock the
handleCors
middleware. My attempt on mocking this:
jest.mock('auth/auth.middleware', () => {
  const actual = jest.requireActual('auth/auth.middleware');
  return {
    __esModule: true,
    ...actual,
    handleCors: jest.fn().mockImplementation(() => Promise.resolve()),
  };
});

And when I run the tests this is the error:
FAIL  __tests__/api/auth/auth.login.test.ts
  ● /api/auth/login › unsuccessful login with wrong API method

    TypeError: (0 , _authMiddleware.handleCors) is not a function

      68 |   res: NextApiResponse,
      69 | ) {
> 70 |   await handleCors(req, res, [httpMethods.POST]);
         |                   ^
      71 |
      72 |   if (req.method === httpMethods.POST) {
      73 |     await requireUsernamePasswordLogin(req, res);

      at handler (pages/api/auth/login.ts:70:19)
      at Object.<anonymous> (__tests__/api/auth/auth.login.test.ts:52:18)

  ● /api/auth/login › successful login

    TypeError: (0 , _authMiddleware.handleCors) is not a function

      68 |   res: NextApiResponse,
      69 | ) {
> 70 |   await handleCors(req, res, [httpMethods.POST]);
         |                   ^
      71 |
      72 |   if (req.method === httpMethods.POST) {
      73 |     await requireUsernamePasswordLogin(req, res);

      at handler (pages/api/auth/login.ts:70:19)
      at Object.<anonymous> (__tests__/api/auth/auth.login.test.ts:67:18)

The error seems to be triggered before actually entering the
handleCors
middleware function.
Any ideas on how to mock the handleCors middleware?

0 Replies