Как выполнить модульное тестирование и проверить, вызывает ли функция ожидаемый метод firebase в Jest? - PullRequest
2 голосов
/ 21 апреля 2020

В App.ts Я вызываю firebase.auth().signInWithEmailAndPassword(email, password) метод

Теперь я хочу выполнить модульное тестирование, чтобы проверить, что при вызове метода myAuthenticationPlugin.authenticate(email, password) из App.spec.ts он также вызывает метод firebase.auth().signInWithEmailAndPassword(email, password), поскольку это то, что App.ts по существу делает ..

Я пробовал несколько обходных путей безрезультатно.

App.ts

const App= {
    authenticate: async (email, password) => {
        await firebase.auth().signInWithEmailAndPassword(email, password)
  },
}

App.spe c .ts

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

        signInWithEmailAndPassword: jest.fn().mockImplementation()
      }
    }),
    initializeApp: jest.fn()
  }
  return firebase
})

describe('Test for authenticate ()', () => {
    it('signInWithEmailAndPassword ()', () => {
      const email = 'test'
      const password = 'mypassword'
      myAuthenticationPlugin.authenticate(email, password)
      expect(firebase.auth().signInWithEmailAndPassword).toHaveBeenCalled()
    })
  })

Ошибка, которую я получаю

● App.js (Authentication Plugin) › Test for authenticate () › signInWithEmailAndPassword ()

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      44 |       const password = 'mypassword'
      45 |       myAuthenticationPlugin.authenticate(email, password)
    > 46 |       expect(firebase.auth().signInWithEmailAndPassword).toHaveBeenCalled()
         |                                                          ^
      47 |     })
      48 |   })
      49 | })

      at Object.<anonymous> (tests/unit/App.spec.ts:46:58)

1 Ответ

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

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

app.ts:

import firebase from 'firebase/app';

const App = {
  authenticate: async (email, password) => {
    await firebase.auth().signInWithEmailAndPassword(email, password);
  },
};

export default App;

app.test.ts:

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

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

describe('61352544', () => {
  it('should pass', async () => {
    const email = 'example@gmail.com';
    const password = '123';
    await App.authenticate(email, password);
    expect(firebase.auth().signInWithEmailAndPassword).toBeCalledWith(email, password);
  });
});

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

 PASS  stackoverflow/61352544/app.test.ts (12.122s)
  61352544
    ✓ should pass (9ms)

----------|---------|----------|---------|---------|-------------------
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.061s

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

...