0

I have a simple function like this, I would like to mock the return value of authentication.getAccessToken() with a valid accessToken, I am having hard time doing this. Tried different ways but couldn't succeed, Can someone help me on this?

  import decodeJWT from "jwt-decode";      
  import authentication from "@kdpw/msal-b2c-react";

  export const testfunction = () => {
      const jwt = decodeJWT(authentication.getAccessToken());
      var current_time = Date.now() / 1000;
      var remaining_time = jwt.exp - current_time;
      return "testing done"
    }

Following is the unit test which I have been trying, As authentication.getAccessToken() doesn't get any value it is throwing InvalidToken error.

    import * as commonUtil from "../commonUtil";

    describe('test test function', () => {
       it("Mock", () => {        
          //The following runs but test fails due to null return
          const authentication = require("@kdpw/msal-b2c-react");
          authentication.getAccessToken = jest.fn().mockReturnValue(false);
          expect(commonUtil.testfunction()).toBe(false)         
          }); 
       });

Error message

Comparing two different types of values. Expected boolean but received null.

1 Answer 1

1

You need to import authentication within your test.

See CodeSandbox example. Open with editor to check out the unit tests.

In short, you need to do something like this.

test('test test function', () => {
    const resp = { data: '' };
    import authentication from "@kdpw/msal-b2c-react";
    authentication.getAccessToken = jest.fn().mockReturnValue("eyJ0eXAiOiJKV1QiLCJhbdjhkbE5QNC1jNTdkTzZR...");
    expect(commonUtil.testfunction()).toEqual("testing done")
});

Use describe to wrap test cases that uses mocked authentication so the mocked function will only stay local in that specific describe and everything outside it will use the real authentication.getAccessToken().

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response but the authenticaion that I was referring is from @kdpw/msal-b2c-react package. I am having hard time using your sample and get it working. I tried const authentication = require("@kdpw/msal-b2c-react"); or const authentication = require("@kdpw/msal-b2c-react").authentication; but nothing works. And the final received return is always null.
@VenkateshMarepalli You don't have to follow my import method strictly. You can use your regular import authentication from "@kdpw/msal-b2c-react"; instead. Try that and let me know how it goes.
@VenkateshMarepalli Now I understand why you're mocking getAccessToken(). Check out my updated CodeSandbox above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.