简体   繁体   English

Jest Mock 函数的返回值

[英]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.我有一个像这样的简单 function ,我想用有效的 accessToken 模拟 authentication.getAccessToken() 的返回值,我很难做到这一点。 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.以下是我一直在尝试的单元测试,因为 authentication.getAccessToken() 没有得到任何值,它会抛出 InvalidToken 错误。

    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.您需要在测试中导入authentication

See CodeSandbox example.请参阅CodeSandbox示例。 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() .使用describe来包装使用模拟authentication的测试用例,因此模拟的 function 将仅在该特定describe中保持本地,并且它之外的所有内容都将使用真正的authentication.getAccessToken()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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