Как издеваться над firebase.auth.UserCredential jest? - PullRequest
0 голосов
/ 23 апреля 2020

Это мой текущий макет, я хочу, чтобы createUserWithEmailAndPassword вернул firebase.auth.UserCredential, чтобы я мог проверить, вызывается ли он в моем App.ts

App.spe c. ts

import myAuthenticationPlugin from 'authenticationPlugin/App'
import firebase from 'firebase/app'
jest.mock('firebase/app', () => {
  return {
    auth: jest.fn().mockReturnThis(),
    currentUser: {
      email: 'test',
      uid: '123',
      emailVerified: true
    },

    signInWithEmailAndPassword: jest.fn(),
    createUserWithEmailAndPassword:jest.fn(() => {
      return {
        user:{
          sendEmailVerification:jest.fn(),
        },
      }
    }),
    initializeApp:jest.fn()
  };
});

 describe('Test for signup (email,password)',() => {

    it('createUserWithEmailAndPassword ()',async () => {  //this works
      await myAuthenticationPlugin.signup(email, password)
      expect(firebase.auth().createUserWithEmailAndPassword).toBeCalledWith(email, password)
    })

    it('sendEmailVerification()',async ()=>{
      await myAuthenticationPlugin.signup(email, password)
      const userCredential= await firebase.auth().createUserWithEmailAndPassword(email,password)
      if(userCredential.user!=null){
      expect(userCredential.user.sendEmailVerification).toBeCalled() //this fails as i'm not able to mock properly
      }
    })
  })

Приложения

import firebase from 'firebase/app'
import 'firebase/auth'
import './Init'
const App= {
 signup: async (email, password) => {
    const userCredential = await firebase.auth().createUserWithEmailAndPassword(email, password)
    await userCredential.user.sendEmailVerification()
    return `Check your email for verification mail before logging in`
  },
}
export default App

1 Ответ

2 голосов
/ 24 апреля 2020

Вот решение для модульного теста:

app.ts:

import firebase from 'firebase/app';

const App = {
  signup: async (email, password) => {
    const userCredential = await firebase.auth().createUserWithEmailAndPassword(email, password);
    await userCredential.user!.sendEmailVerification();
    return `Check your email for verification mail before logging in`;
  },
};
export default App;

app.test.ts:

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

const userCredentialMock = {
  user: {
    sendEmailVerification: jest.fn(),
  },
};

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

describe('61391590', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', async () => {
    const email = 'example@gmail.com';
    const password = '123';
    const actual = await App.signup(email, password);
    expect(actual).toEqual('Check your email for verification mail before logging in');
    expect(firebase.auth().createUserWithEmailAndPassword).toBeCalledWith(email, password);
    expect(userCredentialMock.user?.sendEmailVerification).toBeCalled();
  });
});

Результаты модульного теста со 100% покрытием:

 PASS  stackoverflow/61391590/app.test.ts (12.946s)
  61391590
    ✓ should pass (7ms)

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

исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61391590

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...