-1
import assert from 'assert';
const fn = () => { throw new Error('bar') }

describe('fn()', () => {
  it('should throw "foo"', () => {
    assert.throws(fn, Error, 'foo');
  });
});

It (incorrectly) says the test passed:

fn()
    √ should throw "foo"
    
  1 passing (8ms)

This is wrong because fn() throws 'bar' not 'foo'. What am I doing wrong?

GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
  • I assume you are using chai as assertion framework? Take a look at: https://stackoverflow.com/questions/21587122/mocha-chai-expect-to-throw-not-catching-thrown-errors – n9iels Aug 01 '20 at 19:06
  • ``"foo"`` is an instance of ``String``, since you didn't do ``throw new Error("foo");``. – Take-Some-Bytes Aug 01 '20 at 19:11
  • @n9iels I'm using Mocha. – GirkovArpa Aug 01 '20 at 19:53
  • @Take-Some-Bytes I updated my code to `throw new Error('foo')` and now all I get is `Error: foo`, instead of the test passing. – GirkovArpa Aug 01 '20 at 19:53
  • I made progress. It passes the test if the function throws an error, and fails otherwise. But it passes for ALL error messages. I need it to pass only for a SPECIFIC error message. – GirkovArpa Aug 01 '20 at 20:04

2 Answers2

0

I had to install chai and use its assert and expect.

import chai from 'chai';
const { assert, expect } = chai;
const fn = () => { throw 'foo' }

describe('fn()', () => {
  it('should throw "foo"', () => {
    expect(fn).to.throw('foo');
  });
});
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
  • 1
    Potential problem with this is: what happeneds if `fn()` does not throw anything? Better would be to store the error message in a variable and perform the assertion outside below the catch – n9iels Aug 01 '20 at 20:16
0

As per the docs, if you pass a constructor the library performs instanceof validation, if you want to check props then use a validation object or Regex e.g.

assert.throws(fn, {
  name: 'Error',
  message: 'foo'
});
James
  • 80,725
  • 18
  • 167
  • 237