Skip to content

Compare arrays of Errors in Chai

I have a validator method that returns an array with Errors. I want to create a unit test that compares this errors, but I can’t use expect(fn).to.throw since I don’t throw the errors, just return them. This is my approach but I get AssertionError: expected [ Array(2) ] to have the same members as [ Array(2) ]

  it.only('catches when first row is a single-column', function () {
    const worksheet = readWorksheet(Buffer.from(
      'Table 1n' +
        'action,Email,firstname,lastname,channelIdsn' +
    const errors = validateHeaderRow(worksheet, requiredColumnNames, columnAliases)

      new Error('Missing required column/s action'),
      new Error('The column label "Table 1" is invalid'),

Previously we used Jasmine .toEqual which worked, but now we are switching to Mocha-Chai-Sinon and I cannot get it to work.



As Error objects have many properties and are not so simple to compare, I would make the problem easier by mapping the message property from each Error object and comparing against that. The assertion becomes:

expect( => err.message)).to.deep.equal([
    'Missing required column/s action',
    'The column label "Table 1" is invalid',

This solution verifies that our array of Errors contains each Error object that we expect it to.