【问题标题】:Expect sub Methods to throw an error when parent method throws an error in JEST当父方法在 JEST 中抛出错误时,期望子方法抛出错误
【发布时间】:2020-04-28 18:40:45
【问题描述】:
  • 在方法signup里面,我在嘲笑 firebase.auth().createUserWithEmailAndPassword 并让它抛出 一个error
  • 所以现在我希望父方法,即 signup 也应该抛出,因为 signup 方法的 sub-method 已经抛出错误
  • 但是测试用例失败了,我在这里缺少什么?

App.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

App.spec.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 |   })

【问题讨论】:

    标签: javascript typescript unit-testing firebase-authentication jestjs


    【解决方案1】:

    这有几个问题:

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

    首先,传递给expect的参数必须是函数,所以这几乎正确:

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

    ...但它也行不通。这是因为.toThrow() 函数用于检测同步错误抛出,而不是用于检查被拒绝的 Promise。你需要使用.rejects 来告诉 Jest 解开 Promise:

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

    【讨论】:

    • 感谢您分享您的专业知识,极大地帮助了我,解决了我的问题并帮助我了解了 jest 在内部的工作原理:)
    • 非常感谢雅各布。 @Phil 仅供参考,您还可以检查错误消息本身,例如: test('检查 newUserCreated 函数是否抛出', async () => { // 创建数据库快照 const snap = testEnv.database.makeDataSnapshot({ id: testUserId, firstName: 'Dan Pralea' }, testUserPath); await expect(wrapped(snap)).rejects.toThrowError('Cannot read property \'make\' of undefined'); });
    猜你喜欢
    • 2015-03-08
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多