javascript - 模拟 firebase 模块后模拟 firebase auth 方法的实现

标签 javascript typescript unit-testing firebase-authentication jestjs

我想更改 jest.mock 内部方法的实现所以我可以检查我的应用程序如何对不同的边缘情况使用react,所以我这样做了,但是 typescript 不允许我模拟 firebase.auth().currentUser方法...我在下面显示我的代码和错误

app.js

import firebase from 'firebase/app'
import 'firebase/auth'
import './Init'

const App = {
getLoggedInUser: () => {
    const currentUser = firebase.auth().currentUser
    if (currentUser) {
      return {
        email: firebase.auth().currentUser.email,
        userId: firebase.auth().currentUser.uid,
        isEmailVerified: firebase.auth().currentUser.emailVerified
      }
    } else {
      return undefined
    }
  },
  isAuthenticated: () => {
    return !!((App.getLoggedInUser() && App.getLoggedInUser().isEmailVerified === true))
  },
}
export default App

app.spec.ts
import myAuthenticationPlugin from 'authenticationPlugin/App'
import firebase from 'firebase/app'

jest.mock('firebase/app', () => {
  const userCredentialMock = {
    user: {
      sendEmailVerification: jest.fn()
    }
  }
  return {
    auth: jest.fn().mockReturnThis(),
    currentUser: {
      email: 'test',
      uid: '123',
      emailVerified: true
    },
    signInWithEmailAndPassword: jest.fn(),
    createUserWithEmailAndPassword: jest.fn(() => userCredentialMock),
    sendPasswordResetEmail: jest.fn(),
    signOut: jest.fn(),
    onAuthStateChanged: jest.fn(),
    initializeApp: jest.fn()
  }
})

  describe('Test for isAuthenticated ()', () => {
    afterEach(() => {
      jest.resetAllMocks()
    })
    it('The API should return a boolean value telling us, If the user is authenticated to access the resources or not', () => {
      expect(myAuthenticationPlugin.isAuthenticated()).toBe(true)
    })

    firebase.auth().currentUser = jest.fn(() => {
      return {
        email: 'test',
        uid: '123',
        emailVerified: false
      }
    })

    it('Check false', () => {
      expect(myAuthenticationPlugin.isAuthenticated()).toBe(false)
    })
  })

我得到错误
 FAIL  tests/unit/App.spec.ts
  ● Test suite failed to run

    TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    tests/unit/App.spec.ts:44:5 - error TS2740: Type 'Mock<{ email: string; uid: string; emailVerified: boolean; }, []>' is missing the following properties from type 'User': delete, emailVerified, getIdTokenResult, getIdToken, and 31 more.

    44     firebase.auth().currentUser = jest.fn(() => {
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~

我现在对如何继续为我的应用程序测试不同的边缘案例感到困惑,这是否有某种方式?

最佳答案

你需要模拟firebase.auth方法及其返回值为 currentUser .

例如。app.ts :

import firebase from 'firebase/app';

const App = {
  getLoggedInUser: () => {
    const currentUser = firebase.auth().currentUser;
    if (currentUser) {
      return {
        email: currentUser.email,
        userId: currentUser.uid,
        isEmailVerified: currentUser.emailVerified,
      };
    } else {
      return undefined;
    }
  },
  isAuthenticated: () => {
    return !!(App.getLoggedInUser() && App.getLoggedInUser()!.isEmailVerified === true);
  },
};
export default App;
app.test.ts :

import App from './app';
import firebase from 'firebase/app';

jest.mock('firebase/app', () => {
  return {
    auth: jest.fn(),
  };
});

describe('61408137', () => {
  it('should return user', () => {
    (firebase.auth as jest.Mocked<any>).mockReturnValueOnce({
      currentUser: { email: 'example@gmail.com', uid: 1, emailVerified: true },
    });
    const actual = App.getLoggedInUser();
    expect(actual).toEqual({
      email: 'example@gmail.com',
      userId: 1,
      isEmailVerified: true,
    });
  });

  it('should return undefined', () => {
    (firebase.auth as jest.Mocked<any>).mockReturnValueOnce({});
    const actual = App.getLoggedInUser();
    expect(actual).toBeUndefined();
  });
});

带有覆盖率报告的单元测试结果:

 PASS  stackoverflow/61408137/app.test.ts (9.822s)
  61408137
    ✓ should return user (3ms)
    ✓ should return undefined (1ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |    87.5 |       50 |      50 |    87.5 |                   
 app.ts   |    87.5 |       50 |      50 |    87.5 | 17                
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        11.683s

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61408137

关于javascript - 模拟 firebase 模块后模拟 firebase auth 方法的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61408137/

相关文章:

javascript - 如何停止 bootstrapValidator 来验证隐藏的输入字段?

visual-studio - 调试正在 Visual Studio 2010 中测试的代码

unit-testing - 如何使用多种方法模拟第三方结构并在依赖于第三方结构的端点上执行单元测试?

angular - 未捕获( promise )未定义

node.js - 同步运行 Node sqlite3代码

.net - 如何模拟 System.Data.Linq.Table<MyClass>

javascript - 使用 ng-click Angularjs 调用多个方法

javascript - Angular 1 自定义指令未执行

javascript - NodeJS 在函数完成之前响应

javascript - 检查型号 "dirtiness"