嘲笑一个函数的返回值

时间:2019-10-03 00:34:45

标签: javascript reactjs unit-testing jestjs

我有一个像这样的简单函数,我想用有效的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.

1 个答案:

答案 0 :(得分:0)

您需要在测试中导入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的测试用例,这样模拟函数将仅在该特定describe中保持本地状态,并且其外部的所有内容都将使用真实的authentication.getAccessToken()