2017-05-05 49 views
0

我正在編寫一個單元測試來測試我的postgres模式。我使用node-pg,mocha,sinon和chai。當失敗時測試不會調用done()

這工作 - 測試通過沒有問題:

describe('When adding a user',()=> { 
    it('should reject since email is used somewhere else', (done)=> { 
    pool.query(`INSERT INTO users(email, id, token) 
       VALUES($1, $2, $3)`, ['[email protected]', '12346', 'fooToken']) 
    .then((result)=> { 
     console.log('nothing in here runs, you will not see this'); 
     done() 
    }) 
    .catch((result) => { 
     result.constraint.should.have.string('email_already_exists'); 
     done(); 
    }) 
    }) 
}); 

但是,爲了確保我沒有得到一個誤報,我改變斷言到result.constraint.should.not.have.string('email_already_exists');故意使測試失敗。

而不是測試失敗,我得到Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

我在做什麼?

+1

如果您正在測試基於承諾的代碼,您應該考慮使用Mocha的內置[promises支持](https://mochajs.org/#working-with-promises)。更容易防止這樣的問題。 – robertklep

+0

@robertklep這個承諾如何支持在節點中測試2次讀取? http://stackoverflow.com/questions/43690868/how-to-assert-stubbed-fetch-more-than-once/43806205#43806205 – dman

+1

一個很好的例子:https://coderwall.com/p/axugwa/cleaning-這個問題中的數據庫之間的摩卡測試與pg-promise –

回答

1

如果你還是想用承諾這一點,問題是,在承諾未處理的異常不幸的是沒有傳播,而是被忽略。因此,沒有人呼叫摩卡的done方法,導致超時。

如文檔here所示,將偵聽器附加到Node的unhandledRejection事件應該證明這一點。

如果您修改的原始代碼和呼叫添加到無極的done方法(這不是摩卡的done方法!),那麼你就可以捕獲所有的錯誤,並通過他們向摩卡的done方法:

it('tests something', done => { 
    pool.query('...') 
    .then(result => { 
     // ... 
    }) 
    .catch(result => { 
     // assertion that fails 
    }) 
    .done(result => {}, error => { done(error); }); 
}); 

請注意,Promise.done()還不是標準的一部分,但仍受許多實現的支持。例如參見here

0

答:

的承諾鏈節點-PG導致期間測試這個奇怪的問題。如果我關閉回調的工作,那麼沒有問題:

describe('When adding a user',()=> { 
    it('should reject since email is used somewhere else', (done)=> { 
    function callback(err, result) { 
     err.constraint.should.not.have.string('email_already_exists'); 
     done(); 
    } 
    pool.query(`INSERT INTO users(email, id, token) 
       VALUES($1, $2, $3)`, ['[email protected]', '12346', 'fooToken'], callback) 
    }) 
}); 
相關問題