Jest: Async / Await متوقع (). toThrow () لا يعمل كما هو متوقع

تم إنشاؤها على ١٢ فبراير ٢٠١٨  ·  5تعليقات  ·  مصدر: facebook/jest

أحاول التأكيد على أن الوعد يلقي بخطأ مع Async / Await.

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  expect(async () => {
    await throws()
  }).toThrow()
})

هذا ما أحصل عليه:

● promise throws

expect(function).toThrow(undefined)

Expected the function to throw an error.
But it didn't throw anything.

أي أفكار؟ ألا يدعم Jest هذا؟ أم أنني أستخدمه بشكل غير صحيح؟

التعليق الأكثر فائدة

لما؟

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  await expect(throws()).rejects.toThrow()
})

تم حل هذه المشكلة ، يرجى قراءة المستندات قبل التعليق على المشكلات القديمة. https://jestjs.io/docs/en/asynchronous#resolves -rejects

ال 5 كومينتر

لكن هذا يمر:

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  let message = false
  try {
    await throws()
  } catch (e) {
    message = e.message
  }
  expect(message).toBeTruthy()
})

مرشح الوظيفة الأساسية.

لما؟

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  await expect(throws()).rejects.toThrow()
})

تم حل هذه المشكلة ، يرجى قراءة المستندات قبل التعليق على المشكلات القديمة. https://jestjs.io/docs/en/asynchronous#resolves -rejects

لما؟

async function throws () {
  throw new Error('hello world')
}

test('promise throws', async () => {
  await expect(throws()).rejects.toThrow()
})

تم حل هذه المشكلة ، يرجى قراءة المستندات قبل التعليق على المشكلات القديمة. https://jestjs.io/docs/en/asynchronous#resolves -rejects

الشيء المهم في الحل هو await و expect . وإلا فإن الشيكات الخاصة بك سوف تمر دائمًا.
بدلاً من ذلك ، يمكنك أيضًا إرجاع المتوقع كما يفعلون في المستندات.

هل كانت هذه الصفحة مفيدة؟
0 / 5 - 0 التقييمات