繁体   English   中英

Jest Mock 函数的返回值

[英]Jest Mock a function's return value

我有一个像这样的简单 function ,我想用有效的 accessToken 模拟 authentication.getAccessToken() 的返回值,我很难做到这一点。 尝试了不同的方法但无法成功,有人可以帮助我吗?

  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"
    }

以下是我一直在尝试的单元测试,因为 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)         
          }); 
       });

错误信息

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

您需要在测试中导入authentication

请参阅CodeSandbox示例。 使用编辑器打开以检查单元测试。

简而言之,你需要做这样的事情。

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")
});

使用describe来包装使用模拟authentication的测试用例,因此模拟的 function 将仅在该特定describe中保持本地,并且它之外的所有内容都将使用真正的authentication.getAccessToken()

暂无
暂无

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

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