首页 > 解决方案 > React 测试模拟实现一,使用模拟函数

问题描述

我正在实现一个用于 firebase 身份验证的模拟功能,我已经像这样模拟了 firebase 模块:

jest.mock("../../lib/api/firebase", () => {
  return {
    auth: {
      createUserWithEmailAndPassword: jest.fn(() => {
        return {
          user: {
            uid: "fakeuid",
          },
        };
      }),
      signOut: jest.fn(),
    },
    firestore: {
      collection: jest.fn(() => ({
        doc: jest.fn(() => ({
          collection: jest.fn(() => ({
            add: jest.fn(),
          })),
          set: jest.fn(),
        })),
      })),
    },
  };
});

现在createUserWithEmailAndPassword返回一个用户 uid 以在注册时伪造 firebase 响应。我在我的测试中这样使用它:

.
.
.
 await wait(() => {
      expect(auth.createUserWithEmailAndPassword).toHaveBeenCalled();
      expect(history.location.pathname).toBe("/dashboard");
      expect(getByText("You succesfully signed up!")).toBeInTheDocument();
    });

它工作得很好,但是如果我希望返回的值对于一个测试来说是不同的呢?我看到有 mockImplementationOnce 似乎是正确的道路,但我正在努力实现它,有什么帮助吗?谢谢,F。

标签: reactjsfirebasejestjsreact-testing-library

解决方案


你可以mockReturnValueOnce这样使用:

auth.createUserWithEmailAndPassword
.mockReturnValueOnce(/* your desired return value here */)

只需确保在调用测试之前模拟返回值。auth.createUserWithEmailAndPassword

例如:

auth.createUserWithEmailAndPassword
.mockReturnValueOnce({user: { uid: 'mocked uid'}})

auth.createUserWithEmailAndPassword()

// Insert your expect statement(s) here
...

推荐阅读