1. assert-rejects
Assert that a promise eventually rejects
assert-rejects
Package: assert-rejects
Created by: LinusU
Last modified: Mon, 13 Jun 2022 03:33:45 GMT
Version: 1.0.0
License: MIT
Downloads: 8,114
Repository: https://github.com/LinusU/assert-rejects

Install

npm install assert-rejects
yarn add assert-rejects

Assert Rejects

Assert that a promise eventually rejects

Installation

 npm install --save assert-rejects

Usage

 const assertRejects = require('assert-rejects')

describe('Something', () => {
  it('rejects', () => {
    const promise = doSomethingThatShouldReject()

    return assertRejects(promise)
  })

  it('rejects with specific code', () => {
    const promise = readFileThatDoesntExists()

    return assertRejects(promise, err => err.code === 'ENOENT')
  })
})

API

assertRejects(promise[, error][, message])

Expects the promise to reject. Returns a new promise that will resolve once the provided promise is resolved.

If specified, error can be a constructor, RegExp, or validation function.

If specified, message will be the message provided by the AssertionError if the promise fails to reject.

Validate instanceof using constructor:

 assertRejects(
  Promise.reject(new Error('Wrong value')),
  Error
)

Validate error message using RegExp:

 assertRejects(
  Promise.reject(new Error('Wrong value')),
  /value/
)

Custom error validation:

 assertRejects(
  Promise.reject(new Error('Wrong value')),
  (err) => ((err instanceof Error) && /value/.test(err)),
  'unexpected rejection'
)

Note that error can not be a string. If a string is provided as the second argument, then error is assumed to be omitted and the string will be used for message instead. This can lead to easy-to-miss mistakes:

 // THIS IS A MISTAKE! DO NOT DO THIS!
assertRejects(myPromise, 'missing foo', 'did not reject with expected message')

// Do this instead.
assertRejects(myPromise, /missing foo/, 'did not reject with expected message')

Dependencies

RELATED POST

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin