Home > Software engineering >  how to create instance of class with jest
how to create instance of class with jest

Time:05-23

I am a beginner in writing tests and in jest also. I want to test that this function to be called and return the success promise. I write a unit test for function using jest. The function gets like parameter instance of class that I can't create because its constructor requires parameters that I haven't access. I have a lot of functions that have Session like parametrs. How can test function when you cant provide parametrs for it? Can I mock instance of class or function and handle it without parameter?

async initFlow(session: Session) {
    const nextAtomId = session.userInput.getParam('NEXT_ATOM');
    if (nextAtomId) {
        const nextAtom = await AtomManager.findActiveAtom(nextAtomId);
        if (!session.features.useTerms || ['beforeTerms', 'TermsAndConditions'].includes(nextAtom.type)) {
            return AtomProcessor.processAtom(session, nextAtom);
        }
    }

    const start = await AtomManager.getStartAtom(`${session.botId}`);
    if (!start) {
        throw new Error('Could not find start atom');
    }

    session.user = await UserManager.getGlobalUser(session); // getGlobalUser makes initUser under the hood.
    return AtomProcessor.processAtom(session, start);
}

CodePudding user response:

You can mock both AtomManager & UserManager and provide a mock session object when calling initFlow.

jest.mock("./path/to/AtomManager");
jest.mock("./path/to/UserManager");

it("works", async () => {
  const mockSession = {
    userInput: {
      getParam: jest.fn(),
    },
    botId: "123",
  };
  const mockUser = "user123";
  const mockStartAtom = "atom123";
  AtomManager.getStartAtom.mockResolveValue(mockStartAtom);
  UserManager.getGlobalUser.mockResolveValue(mockUser);

  await initFlow(mockSession);

  expect(mockSession.user).toBe(mockUser);
  expect(AtomManager.getStartAtom).toHaveBeenCalledTimes(1);
  expect(AtomManager.getStartAtom).toHaveBeenCalledWith(mockSession.botId);
  expect(UserManager.getGlobalUser).toHaveBeenCalledTimes(1);
  expect(UserManager.getGlobalUser).toHaveBeenCalledWith(mockSession);
  expect(AtomProcessor.processAtom).toHaveBeenCalledTimes(1);
  expect(AtomProcessor.processAtom).toHaveBeenCalledWith(mockSession, mockStartAtom);
});

The snippet above makes the following assertions:

  1. AtomManager.getStartAtom is called once and it's called with the mock botId.

  2. UserManager.getGlobalUser is called once and it's called with the mock session object.

  3. UserManager.getGlobalUser has successfully added the user property on the passed session object.

  4. AtomProcessor.processAtom is called once and it's called with the mock session and the mock start atom.

You can similarly the test other branches of code.

  • Related