简体   繁体   中英

How to test for a specific error message in Mocha?

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?

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');
  });
});

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 eg

assert.throws(fn, {
  name: 'Error',
  message: 'foo'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM