dimanche 8 décembre 2019

Testing function with inner function that should be mocked - JEST

I have problem with testing this function. I don't know how can I test function checkAuth when decode is mocked.

import decode from "jwt-decode";

export const checkAuth = () => {
  const token = localStorage.getItem("token");
  if (!token) {
    return false;
  }

  try {
    const { exp } = decode(token);
    if (exp < new Date().getTime() / 1000) {
      return false;
    }
  } catch (e) {
    console.log(e); // 'Invalid token specified: Cannot read property \'replace\' of undefined'
    return false;
  }

  return true;
};

My test isn't work. It takes original function.

import { Auth, AuthAdmin, checkAuth, AppContent, AuthApp } from "./Auth";
import LocalStorageMock from "../../../mocks/localStorageMock";
import decode from "jwt-decode";

global.localStorage = new LocalStorageMock();

describe("auth", () => {
  localStorage.setItem("token", "fake_token_user");
  const token = localStorage.getItem("token");

  it("allows the user to login successfully", async () => {
    const decode = jest.fn(token => {
      return {
        exp: new Date().getTime() / 1000 - 1,
        iat: 1575751766,
        userData: { isAdmin: true, login: "one92tb", userId: 1 }
      };
    });
    //const { exp } = decode(token);

    expect(token).toBeDefined();
    expect(checkAuth()).toBe(true) // It runs original decode function
  });
});

Can someone explain to me how to solve that problem? I spent few hours to resolve this problem, but still I don't understand...

PS. Sorry for my english.

Aucun commentaire:

Enregistrer un commentaire