簡體   English   中英

Mocha / Chai:測試精確的投擲錯誤結果

[英]Mocha/Chai: Test for exact throw error result

有一個簡單的方法,它會拋出一個錯誤:

methods.js

insertItem = new ValidatedMethod({
    name    : 'article.insert.item',
    validate: new SimpleSchema({
        parent: { type: SimpleSchema.RegEx.Id }
        value : { type: String }
    }).validator(),

    run({ parent, value}) {
        var isDisabled = true
        if (isDisabled)
            throw new Meteor.Error('example-error', 'There is no reason for this error :-)')
    }
})

現在我想對這個錯誤做一個mocha測試。 所以我提出了這個,這是有效的:

server.test.js

it('should not add item, if element is disabled', (done) => {
    const value = 'just a string'

    function expectedError() {
        insertItem.call(
            {
                parent: '12345',
                value
            }
        )
    }

    expect(expectedError).to.throw
    done()
})

在此之前一切正常。

問題

但我想測試確切的錯誤消息。

我已經試過了

expect(expectedError).to.throw(new Meteor.Error('example-error', 'There is no reason for this error :-)'))

但它給了我一個失敗的測試:

Error: expected [Function: expectedError] to throw 'Error: There is no reason for this error :-) [example-error]'

我認為這些文檔在這方面有點誤導/混淆 - 只需從您的expect刪除new運算符,它將與拋出的錯誤相匹配:

expect(expectedError).to.throw(Meteor.Error('example-error', 'There is no reason for this error :-)'))

我在這篇文章中發現我需要像這樣寫:

expect(expectedError).to.throw(Meteor.Error(), 'example-error', 'This is an error');

請注意,錯誤消息位於Error()之后,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM