2016-04-02 5 views
3

私は約束を返す関数をテストするテストスイートを書いています。これらのテストの共通テーマの1つは、約束している関数が無効な引数を渡したときにエラーを正しくスローするかどうかを確認する必要があることです。私はshould.throwsを使って試しましたが、コードを見て見ると、約束通りに動作するようには設計されていません。約束事のためにshould.throwsを模倣するshouldjs関数が存在しますか?

私は、私は必要な機能を取得するには、以下のユーティリティ関数を作っています

var TestUtil = module.exports; 
 
var should = require('should'); 
 

 
/** 
 
* Checks if a promise chain throws an error, and optionally that the error includes 
 
* the given errorMsg 
 
* @param promise {String} (optional) error message to check for 
 
* @param errorMsg 
 
*/ 
 
TestUtil.throws = function(promise, errorMsg) { 
 
    return promise 
 
    .then(function(res) { 
 
throw new Error(); // should never reach this point 
 
    }) 
 
    .catch(function(e) { 
 
if (errorMsg) { 
 
    e.message.should.include(errorMsg); 
 
} 
 
should.exist(e); 
 
    }); 
 
};

これと同じことをやっshouldjs機能が存在していますか?この一回限りの機能を使用するのではなく、チェックのためにshouldjs APIを使用するだけでテストをまとめることができます。

+2

は.rejectedWithは、あなたが探していたものではありませんか? –

+0

私は '.then(...).catch(...)'の代わりに['.then(...、...)']を使う必要があると思うでしょう。](http://stackoverflow.com/q/24662289/1048572 ) ここに? – Bergi

答えて

1

私が探しているものは.rejectedWithで、これはshouldjsの約束アサーション関数の1つです。あなたはそう(shouldjsのAPIドキュメントから直接コピー)のようにそれを使用します。

function failedPromise() { 
 
    return new Promise(function(resolve, reject) { 
 
    reject(new Error('boom')) 
 
    }) 
 
} 
 
failedPromise().should.be.rejectedWith(Error); 
 
failedPromise().should.be.rejectedWith('boom'); 
 
failedPromise().should.be.rejectedWith(/boom/); 
 
failedPromise().should.be.rejectedWith(Error, { message: 'boom' }); 
 
failedPromise().should.be.rejectedWith({ message: 'boom' }); 
 

 
// test example with mocha it is possible to return promise 
 
it('is async',() => { 
 
    return failedPromise().should.be.rejectedWith({ message: 'boom' }); 
 
});

関連する問題