Skip to content

Instantly share code, notes, and snippets.

@paulodiovani
Last active July 7, 2021 15:49
Show Gist options
  • Save paulodiovani/339a54838f54b80fc43a214184ff695c to your computer and use it in GitHub Desktop.
Save paulodiovani/339a54838f54b80fc43a214184ff695c to your computer and use it in GitHub Desktop.
Testing throwing errors with mocha.
import { expect } from 'chai'
// usage:
// npm install mocha chai
// npx mocha error.test.mjs
describe('catching Error in test', () => {
it('this test must pass', () => {
const fn = () => {
throw new Error('expected error')
}
try {
fn()
// if we are testing if the correct error is thrown,
// must make sure that the fn will thrown an error an,
// otherwise, fail the test
throw new Error('unexpected error')
} catch (err) {
expect(err).to.have.property('message', 'expected error')
}
})
it('this test must fail', () => {
const fn = () => 'no error'
try {
fn()
// the function will not thrown an error, which is unexpected,
// so throwing one afterward will fail the test
throw new Error('unexpected error')
} catch (err) {
expect(err).to.have.property('message', 'expected error')
}
})
it('this test should have failed', () => {
const fn = () => 'no error'
try {
fn()
// if no error is thrown, the test will pass and
// the expectations below will never be reached
} catch (err) {
expect(err).to.have.property('message', 'expected error')
}
})
// to understand better how tests works, we can simply
// throw or not errors, when an error is thrown, the test fails
it('throws error and fails test', () => {
throw new Error('some error')
})
// expectations are not required to pass a test
it('does not thrown an error and pass test', () => {
'no error'
})
});
catching Error in test
✔ this test must pass
1) this test must fail
✔ this test should have failed
2) throws error and fails test
✔ does not thrown an error and pass test
3 passing (7ms)
2 failing
1) catching Error in test
this test must fail:
AssertionError: expected [Error: unexpected error] to have property 'message' of 'expected error', but got 'unexpected error'
+ expected - actual
-unexpected error
+expected error
at Context.<anonymous> (file:///home/diovani/Development/Node/mocha-error-false-positive/error.test.mjs:35:27)
at processImmediate (internal/timers.js:461:21)
2) catching Error in test
throws error and fails test:
Error: some error
at Context.<anonymous> (file:///home/diovani/Development/Node/mocha-error-false-positive/error.test.mjs:54:11)
at processImmediate (internal/timers.js:461:21)
@paulodiovani
Copy link
Author

In case someone wonders,

  • yes we can just use expect(fn).to.throw, but that will not work for async functions
  • and yes, we can use chai-as-promised for async functions

This is just the simplest way to check for errors without depending on chai or other assertion library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment