TypeError: jwt(…).unless is not a function when mocking with Jest

Tags: , , , ,



I am trying to mock the .unless function of express-jwt and currently have this mock setup to compare a JWT with an admin and non admin. This worked perfect until we added .unless and I am not sure the best way to approach the issue.

jest.mock("express-jwt", () => {
  return options => {
    return (req, res, next) => {
      receivedToken = req.headers.authorization.substring(7);
      req.user = { preferred_username: "tester" };
      next();
    };
  };
});

That is the mock. I have tried moving that into a const and adding: mockFun.unless = jest.fn() but to no avail.

Thanks

Edit:

One of the things I tried is below:

jest.mock("express-jwt", () => {
  const mockFunc = () => {
    return (req, res, next) => {
      receivedToken = req.headers.authorization.substring(7);
      req.user = { preferred_username: "tester" };
      next();
    };
  };

  mockFunc.unless = jest.fn();

  return mockFunc
});

Answer

unless is supposed to be a method on a function that jwt() returns while currently it’s a method on jwt itself.

Should be:

jest.mock("express-jwt", () => {
  const mockFunc = jest.fn((req, res, next) => {
   ...
  });

  mockFunc.unless = jest.fn((req, res, next) => {
   ...
  });

  return jest.fn(() => mockFunc);
});


Source: stackoverflow