【问题标题】:Jest, How to mock a function inside an object?开玩笑,如何模拟对象内部的函数?
【发布时间】:2021-09-08 14:34:25
【问题描述】:

我有一个函数会调用 Firebase 和 getIdToken 函数

export const getUserFromDb = async () => {
  const path = "/user";
  const firebaseToken = getAuth().currentUser?.getIdToken(); // here need to get it
  
  console.log(firebaseToken)
  const myInit = {
    headers: {
      Authorization: `token ${firebaseToken}`,
    },
  };

  return API.get(path, myInit);
};

如何模拟这行代码?

const firebaseToken = getAuth().currentUser?.getIdToken();

详情:

getAuth() 是一个从 Firebase 返回 Auth 对象的方法。

currentUser 是来自Auth 对象的属性,具有User 类型。

getIdToken() 是来自currentUser 的方法,它将返回Promise<string>

因此这是我尝试的。

我尝试过的:

我在测试文件的开头模拟了getAuth()getAuth()是一个函数,jest.fn()也是。

jest.mock("firebase/auth", () => { 返回 { getAuth: jest.fn() } }

然后在我的一个测试用例中,我尝试了这个:

it("should login success and setUser", async () => {

    (getAuth as jest.Mock).mockResolvedValueOnce({
        currentUser: {
            getIdToken: jest.fn().mockReturnValueOnce('abc')
        }
    })

    // other stuff here
}

如您所见,我模拟了getAuth() 函数以返回一个currentUser 对象。然后getIdToken() 函数在currentUser 对象中,它将返回一个字符串。

但是当我运行测试时,我得到了这个错误:

控制台.log TypeError:无法读取未定义的属性“currentUser”

它声明currentUser 未定义。但是由于我在测试开始时mockResolvedValueOnce,但它仍然无法获得currentUser的值。

问题

如何模拟这个函数?而我做错了什么?

const firebaseToken = getAuth().currentUser?.getIdToken();

【问题讨论】:

    标签: reactjs unit-testing firebase-authentication jestjs


    【解决方案1】:

    这对我有用:

    const getAuth = jest.fn(() => ({
      currentUser: {
        getIdToken: () => 32,
      }
    }));
    

    【讨论】:

      【解决方案2】:

      最后我像这样嘲笑它:

      (getAuth as jest.Mock).mockReturnValue({
            currentUser: {
              getIdToken: jest.fn().mockReturnValueOnce("abc"),
            },
          });
      

      getAuth 将返回一个currentUser 对象,在currentUser 对象内部有一个getIdToken 函数将返回“abc”作为值。

      然后当“在我的实际代码文件中”这样调用时:

      const firebaseToken = getAuth().currentUser?.getIdToken();
      

      但是在“测试文件”中收到的firebaseToken 的值将是abc,因为我们已经模拟了上面的值。在测试文件中,它不会调用实际的 Firebase 方法,而是调用我上面模拟的方法并取回值。

      【讨论】:

        猜你喜欢
        • 2023-02-03
        • 2020-08-20
        • 1970-01-01
        • 2022-12-24
        • 1970-01-01
        • 2018-12-30
        • 2021-07-03
        • 2018-10-23
        • 1970-01-01
        相关资源
        最近更新 更多