Skip to content
Advertisement

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' +
        'save,foo@example.com,foo,bar,00000A'
    ))
    const errors = validateHeaderRow(worksheet, requiredColumnNames, columnAliases)

    expect(errors).to.have.same.members([
      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.

Advertisement

Answer

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(errors.map((err) => 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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement