使用Google登录进行jest测试Firebase身份验证

4 浏览
0 Comments

使用Google登录进行jest测试Firebase身份验证

我无法弄清如何正确地使用Google登录来嘲弄Firebase身份验证。我有以下代码:

simple.tsx

import React, { Component } from 'react';
import * as firebase from 'firebase'
import { withRouter} from 'react-router-dom';
class simple extends Component {
  signInWithgoogle() {
    var provider = new firebase.auth.GoogleAuthProvider();
    // how to mock provider when simulate click event.
    firebaseApp.auth().signInWithRedirect(provider)
  }
  render() {
    return (
        
    );
  }
export default withRouter(connect(
)(simple));

simple.test.tsx

const mockStore = configureMockStore([thunk]);
const store = mockStore();
describe('', () => {
    test("simulate click button", () =>{
        const withProvider = (
            
                
            
        );
        const wrapper = mount(withProvider);
        wrapper.find('Button').simulate('click');
    });
});

有任何带有示例的帮助将不胜感激?

admin 更改状态以发布 2023年5月22日
0
0 Comments

我也有一种类似的解决方案,如果您决定使用Firebase Auth和Firebase Analytics:

jest.mock('firebase/app', () => {
  const analytics = jest.fn().mockReturnValue({
    logEvent: jest.fn(),
  });
  const auth: any = jest.fn().mockReturnValue({
    signInWithRedirect: jest.fn(),
    getRedirectResult: jest.fn().mockResolvedValue({
      credential: {
        providerId: 'Google',
      },
      user: {
        getIdToken: jest.fn().mockResolvedValue('abc1234'),
      },
      additionalUserInfo: {
        profile: {
          email: 'test@test.com',
          name: 'John Doe',
        },
      },
    }),
  });
  auth.GoogleAuthProvider = class {
    addScope = jest.fn();
  };
  return { auth, analytics };
});

0
0 Comments

Typescript命名空间是经过编译和类型抹消后的一种JS函数。了解了这一点,当然可以给JS函数分配属性。下面是解决方案:

simple.tsx

import React, { Component } from 'react';
import firebase from 'firebase';
import { withRouter } from 'react-router-dom';
class simple extends Component {
  signInWithgoogle() {
    var provider = new firebase.auth.GoogleAuthProvider();
    firebase.auth().signInWithRedirect(provider);
  }
  render() {
    return (
        
    );
  }
}
export default withRouter(simple as any);

simple.spec.tsx

import React from 'react';
import { mount } from 'enzyme';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import simple from './simple';
import firebase from 'firebase';
const mockStore = configureMockStore([thunk]);
const store = mockStore();
const FirebaseAuthProps = {};
jest.mock('firebase', () => {
  const auth = jest.fn();
  const mAuth = { signInWithRedirect: jest.fn() };
  // @ts-ignore
  auth.GoogleAuthProvider = jest.fn();
  // @ts-ignore
  auth.Auth = jest.fn(() => mAuth);
  return { auth };
});
describe('', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });
  test('simulate click button', () => {
    // @ts-ignore
    firebase.auth.mockImplementation(() => new firebase.auth.Auth());
    const withProvider = (
      
        
      
    );
    const wrapper = mount(withProvider);
    expect(wrapper.find('button').text()).toBe('Login with Google');
    wrapper.find('button').simulate('click');
    expect(firebase.auth.GoogleAuthProvider).toBeCalledTimes(1);
    expect(firebase.auth).toBeCalledTimes(1);
    expect(firebase.auth().signInWithRedirect).toBeCalledTimes(1);
  });
});

单元测试结果覆盖率100%:

 PASS  src/stackoverflow/58554920/simple.spec.tsx (15.341s)
  
    ✓ simulate click button (82ms)
------------|----------|----------|----------|----------|-------------------|
File        |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------|----------|----------|----------|----------|-------------------|
All files   |      100 |      100 |      100 |      100 |                   |
 simple.tsx |      100 |      100 |      100 |      100 |                   |
------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        17.245s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58554920

0