assert.throws()函數詳解


assert.throws(block[, error][, message])
Node.js FS模塊方法速查
期望 block 函數拋出一個錯誤。
如果指定 error,它可以是一個構造函數、正則表達式或驗證函數。
如果指定 message,如果 block 因為失敗而拋出錯誤,message 會是由 AssertionError 提供的值。
驗證使用構造函數實例:

assert.throws(
    () => {
        throw new Error('Wrong value');
    },
    Error
);

使用 RegExp 驗證錯誤信息:

assert.throws(
    () => {
        throw new Error('Wrong value');
    },
    /value/
);

自定義錯誤驗證:

assert.throws(
    () => {
        throw new Error('Wrong value');
    },
    function (err) {
        if ((err instanceof Error) && /value/.test(err)) {
            return true;
        }
    },
    'unexpected error'
);

請注意,Error 不能是字符串。如果字符串是作為第二個參數,那么 error 會被假定省略,字符串將會使用 message 替代。這很容易導致丟失錯誤:

// THIS IS A MISTAKE! DO NOT DO THIS!
assert.throws(myFunction, 'missing foo', 'did not throw with expected message');

// Do this instead.
assert.throws(myFunction, /missing foo/, 'did not throw with expected message');


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM