0

I find myself writing this at the start of pretty much all of my unit tests in mocha:

it('should do something', (done) => {
  Vue.config.errorHandler = done;

  // do something aynchronous
});

By default, Vue catches all errors itself and logs them to the console, so mocha can't see them. This code makes sure that thrown errors fail the tests.

Is there a way with mocha to do this without having to start every single async test with this line of code? If I have to write / use a plugin, that's fine.

callumacrae
  • 8,185
  • 8
  • 32
  • 49
  • I don't use Mocha, but every test framework I've ever used has some kind of setup and teardown method to handle these kinds of things. – craig_h Nov 28 '17 at 11:04
  • @craig_h yep, there's a beforeEach hook. It can only be used to fail the test _before_ it runs, not during the testing stage. – callumacrae Nov 28 '17 at 11:05

1 Answers1

-1

Try:

Vue.config.errorHandler = function (err, vm, info) {
  throw err
}

in your test entry.

wxsm
  • 556
  • 4
  • 14
  • This won't work if the error handler is called in a promise. – callumacrae Nov 28 '17 at 11:47
  • It works in my test. Try change your async test from `done` call to async functions. e.g. `it('should...', async () => { //... })` @callumacrae – wxsm Nov 28 '17 at 11:51
  • This fails: `Vue.nextTick(() => { throw new Error('test'); });` - `Vue.nextTick()` uses promises internally. – callumacrae Nov 28 '17 at 11:54
  • Well that was expected. A promise is designed to catch errs internally. If you insist to throw them you can do this `var originalCatch = Promise.prototype.catch; Promise.prototype.catch = function(){throw new Error();return originalCatch.apply(this, arguments);}` – wxsm Nov 28 '17 at 12:01