How to stop test suite after first fail with Jest?

Sometimes, we want to stop test suite after first fail with Jest.

In this article, we’ll look at how to stop test suite after first fail with Jest.

How to stop test suite after first fail with Jest?

To stop test suite after first fail with Jest, we can define our own test function.

For instance w ewrite:

let hasTestFailed = false
const sequentialTest = (name, action) => {
  test(name, async () => {
    if (hasTestFailed) {
      console.warn(`[skipped]: ${name}`)
    } else {
      try {
        await action()
      } catch (error) {
        hasTestFailed = true
        throw error
      }
    }
  })
}
describe('Test scenario 1', () => {
  sequentialTest('that item can be created', async () => {
    expect(true).toBe(false)
  })

  sequentialTest('that item can be deleted', async () => {
    //...
  })
})

to define the sequentialTest function that takes the same arguments as test.

In it, we call test with a function that check a test failed by catching the action test callback.

If an error is thrown, then it’s failed and hasTestFailed is set to true.

And we rethrow the error so the test suite will stop running.

Conclusion

To stop test suite after first fail with Jest, we can define our own test function.