简体   繁体   中英

Jest Mock a function's return value

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM