Ожидайте, что sub Methods выдаст ошибку, когда родительский метод выдаст ошибку в JEST - PullRequest
1 голос
/ 28 апреля 2020
  • Внутри метода signup я высмеиваю firebase.auth().createUserWithEmailAndPassword и заставляю его выбросить error
  • Так что теперь я ожидаю, что родительский метод, то есть signup, должен также выбросить, так как sub-method метода signup выдал ошибку
  • Но тестовые случаи не пройдены. Чего мне здесь не хватает?

Приложение. js

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

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

Приложение.spe c .ts

import myAuthenticationPlugin from 'authenticationPlugin/App'
it('to Throw',async ()=>{
     myAuthenticationPlugin.firebase = {
     auth: jest.fn().mockReturnThis(),
     createUserWithEmailAndPassword: jest.fn(() => {
       throw new Error('Network Error')
     }),
   }
     expect(myAuthenticationPlugin.firebase.auth().createUserWithEmailAndPassword).toThrowError('Network Error')
     expect(await myAuthenticationPlugin.signup).toThrow() // THIS FAILS
    })

Ошибка

 expect(received).toThrow()

    Received function did not throw

      107 |       expect(myAuthenticationPlugin.firebase.auth().createUserWithEmailAndPassword).toThrowError('Network Error')
    > 108 |       expect(await myAuthenticationPlugin.signup).toThrow()
          |                                                   ^
      109 | 
      110 |     })
      111 |   })

1 Ответ

1 голос
/ 28 апреля 2020

У этого есть несколько проблем:

expect(await myAuthenticationPlugin.signup).toThrow() // THIS FAILS

Прежде всего, параметр, передаваемый в expect, должен быть функцией, поэтому почти правильно:

expect(async () => { await myAuthenticationPlugin.signup() }).toThrow()

... но это тоже не сработает. Это связано с тем, что функция .toThrow() предназначена для обнаружения синхронного сброса ошибок, а не для проверки отклоненных обещаний. Вы можете использовать .rejects, чтобы сказать Джесту, что нужно развернуть Обещание:

await expect(myAuthenticationPlugin.signup()).rejects.toThrow()
...