【问题标题】:How do you mock the Firebase SDK when testing action creators in Redux?在 Redux 中测试动作创建者时如何模拟 Firebase SDK?
【发布时间】:2018-11-18 09:07:34
【问题描述】:

我正在使用 React、Redux 和 Firebase 开发 POC。我目前正在研究如何测试动作创建者。我遵循了这个 - https://redux.js.org/recipes/writing-tests#async-action-creators 指南,到目前为止它很有帮助。但是,作为一个简单的示例,我想测试在成功通过 Firebase 进行身份验证后分派了一个动作,就像这样 -

动作创建者

export const authenticate = (username, password) => {
  return dispatch => {
    firebase.auth().signInWithEmailAndPassword(username, password)
      .then(() => {
        dispatch(authenticationSuccessful())
      })
      .catch(() => {

      });
  }
};

动作

const authenticationSuccessful = () => {
  return {
    type: actionTypes.AUTHENTICATION_SUCCESSFUL
  };
};

对于我开玩笑的事情的测试方面,redux-mock-store 和期望。我研究了其他人在这种情况下使用了什么,但我还没有找到明确的答案,我也看过https://www.npmjs.com/package/firebase-mock,但我不知道这是否是社区中的热门选择。

非常感谢您提前提供的任何帮助!

【问题讨论】:

    标签: reactjs unit-testing firebase redux jestjs


    【解决方案1】:

    这个答案符合要求Best way to unit test code that depends on http calls using Jest?

    根据那个答案,这将覆盖signInWithEmailAndPassword 允许您的代码通过而不会碰到firebase。下面的例子可能需要一些调整。不确定dispatch的范围。

    jest.mock('pathToFireBase', () => ({
       signInWithEmailAndPassword(email, password) {
         return Promise.resolve({name: 'someUser'})
       }
    }))
    
    const dispatch = jest.fn();
    firebase.auth().signInWithEmailAndPassword(username, password)
    expect(dispatch.mock.calls.length).toBe(1);
    

    另一个选项(对于 Node.js)是使用类似 VCR 的东西。一个选项是sepia。它由 LinkedIn 构建,因此可能得到更好的维护和测试。使用此工具,您可以记录一次请求、保存响应并在调用时重播。此选项避免了模拟,但通过预定义的响应使 uint 测试保持快速。不过,我不知道有这样的前端选项。


    Firebasemock 看起来是个不错的选择。虽然我看不到signInWithEmailAndPassword。身份验证是通过显式设置状态来完成的。 authentication example.

    mocksdk.auth().changeAuthState({
      uid: 'testUid',
      provider: 'custom',
      token: 'authToken',
      expires: Math.floor(new Date() / 1000) + 24 * 60 * 60,
      auth: {
        isAdmin: true
      }
    });
    mocksdk.auth().flush();
    console.assert(document.location.href === '#/admin', 'redirected to admin');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      相关资源
      最近更新 更多