I am trying to set up a mock function for the Keycloak library for use in my ReactJS application, but so far efforts have been frustrated. I have looked at other questions on mocking node modules in Jest but the answers have not helped as I feel there is missing information in the answers to explain it to non-advanced JS coders like myself.
Here is the mock function I have created for keycloak:
export function useKeyCloak() {
const token = "A random string that is non zero length";
... OTHER CONSTANTS ...
return {
authenticated,
... OTHER PROPERTIES AND METHODS ...
token,
};
}
Per the instructions on mocking node modules in jest, I have put my mock keycloak function in the appropriate folder thus:
src
- __mocks__
- @react-keycloak
- web.js
My setupTests.js file looks like this:
import Adapter from 'enzyme-adapter-react-16';
import { configure } from 'enzyme';
import fetch from './__mocks__/fetch';
global.fetch = fetch;
configure({adapter: new Adapter()});
And lastly, an actual test that wants to run the mock keycloak call looks like this:
import { useKeycloak } from "@react-keycloak/web";
import { shallow } from "enzyme/build";
import User from "../components/User";
import UserInfo from "../components/UserInfo";
jest.mock(useKeycloak);
describe("Keycloak instance", () => {
it("loads keyCloak and returns a token, realmAccess roles and a userProfile", () => {
const userComp = shallow(<User />);
expect(userComp.containsMatchingElement(<UserInfo />)).toBe(true);
});
});
However, this produces the following error when run:
TypeError: (0 , _web.useKeycloak) is not a function
Based on other questions, I understand this is something to do with hoisting, but I just can't seem to get the correct syntax. I've also tried the following in place of jest.mock(useKeycloak):
jest.mock("@react-keycloak/web");
or
jest.mock("@react-keycloak/web", () => ({ useKeycloak: jest.fn() }));
Could someone who is more advanced in JS than me tell me what will work on this line? Ideally a syntax that is confirmed to work in a test. Would be greatly appreciated.