Чаи ожидаем. К ошибкам броска не равны - PullRequest
0 голосов
/ 28 декабря 2018

Я пытаюсь утверждать (используя expect), что выбрасываются определенные ошибки.

Ошибки успешно обнаруживаются, но сравнение ошибок не удается.Это включает в себя thrownCustomError и new CustomError(), а также thrownCustomError и customErrorInstance.Однако кажется, что использование expect().to.throw(CustomError, 'Custom error') работает.

В моем случае я специально пытаюсь утверждать пользовательские ошибки, которые принимают параметры для создания сообщения об ошибке, поэтому использование последнего сравнения довольно громоздко.

Что я здесь не так делаю?Любые предложения приветствуются.

let chai = require("chai");
const expect = chai.expect;
const assert = chai.assert;

class CustomError extends Error{
    constructor() {
        super('Custom error')
    }
}

const throwFn = () => {
    throw new CustomError()
}

const customErrorInstance = new CustomError()

describe('CustomError Test', () => {
    it('should throw a CustomError (new)', () => {
        expect(throwFn).to.throw(new CustomError())
    })

    it('should throw a CustomError (const)', () => {
        expect(throwFn).to.throw(customErrorInstance)
    })

    it('should produce a strictly equal error', (done) => {
        try {
            throwFn()
        } catch (e) {
            assert(e === new CustomError(), 'Thrown error does not match new instance of error')
            assert(e === customErrorInstance, 'Throw error does not match const instance of error')
            done()
        }
        expect.fail()
    })
})

Вывод:

  CustomError Test
    1) should throw a CustomError (new)
    2) should throw a CustomError (const)
    3) should produce a strictly equal error


  0 passing (38ms)
  3 failing

  1) CustomError Test
       should throw a CustomError (new):

      AssertionError: expected [Function: throwFn] to throw 'Error: Custom error' but 'Error: Custom error' was thrown
      + expected - actual


      at Context.it (test.js:19:27)

  2) CustomError Test
       should throw a CustomError (const):

      AssertionError: expected [Function: throwFn] to throw 'Error: Custom error' but 'Error: Custom error' was thrown
      + expected - actual


      at Context.it (test.js:23:27)

  3) CustomError Test
       should produce a strictly equal error:
     AssertionError: Thrown error does not match new instance of error
      at Context.it (test.js:29:4)

Ответы [ 2 ]

0 голосов
/ 30 декабря 2018

После того, как копать глубже, выясняется, что оценка Чай на равенство ошибок ... странно.Ошибка состоит из сообщения и трассировки стека.Поскольку трассировка стека различается в зависимости от того, где была создана ошибка, равенство не может быть достигнуто в пределах expect.to.throw без выброса одного и того же экземпляра.

Единственное решение, которое я могу найти, которое будет утверждать только сообщение об ошибке, таково::

const a = new CustomError()
...
it('should produce a strictly equal error', (done) => {
    try {
        throwFn()
    } catch (e) {
        assert(e.message === a.message, 'Thrown error does not match new instance of error')
        done()
    }
    expect.fail()
})

(Примечание: на момент написания статьи существует открытый PR для удаления / изменения этого поведения https://github.com/chaijs/chai/pull/1220)

0 голосов
/ 29 декабря 2018

Вы тестируете экземпляр каждый раз, поэтому вам нужно сделать throwFn бросок этого экземпляра:

const customErrorInstance = new CustomError()

const throwFn = () => {
    throw customErrorInstance
}

// should throw a CustomError (const)
expect(throwFn).to.throw(customErrorInstance);

первый тест, вам нужно перейти в класс, потому что вы выбрасываете отдельныйэкземпляр в функции, а затем при попытке сравнить с новым экземпляром в ожидаемом, это НИКОГДА не будет верным, по определению экземпляр не строго равен другому экземпляру НИКОГДА:

const throwFn = () => {
    throw new CustomError()
}

expect(throwFn).to.throw(CustomError)

Потому что то, что вымы пытались сравнить экземпляр, выполнив expect(throwFn).to.throw(new CustomError()), это никогда не будет успешным.

Вот твой код, подправленный

let chai = require("chai");
const expect = chai.expect;
const assert = chai.assert;

class CustomError extends Error{
    constructor() {
        super('Custom error')
    }
}

const customErrorInstance = new CustomError()

const throwFn = () => {
    throw customErrorInstance;
}

describe('CustomError Test', () => {
    it('should throw a CustomError (new)', () => {
        expect(throwFn).to.throw(CustomError)
    })

    it('should throw a CustomError (const)', () => {
        expect(throwFn).to.throw(customErrorInstance)
    })

    it('should produce a strictly equal error', (done) => {
        try {
            throwFn()
        } catch (e) {
            assert(e !== new CustomError(), 'Thrown error instance is same as newly constructed! This is impossible!)
            assert(e === customErrorInstance, 'Throw error does not match const instance of error')
            done()
        }
        expect.fail()
    })
})
...