2016-11-12 11 views
1

mochaを使用して、外部Webサービスとの統合テストを実行しています。私は要求/応答の処理のためにsuperagent-promiseを使用し、私はアサーションライブラリとしてexpectを使用しています。「expect」で失敗するのではなく、superagent +を使用したモカのテスト

これらのテストでは、多数のリクエストをまとめてチェーン化する必要があるため、約束が非常に役立っています。しかし、エラーメッセージそのものではなく、タイムアウト(エラーメッセージなし)でテストが失敗していることに気付いています。

it('[MESSAGES-1] cannot be posted without an auth token', function(done) { 
    agent.post(config.webRoot + '/rooms/ABC/messages').send({ 
     content: 'This is a test!' 
    }).end().then(function(res) { 
     // Not expected 
    }, function(err) { 
     expect(err.status).toBe(401) 
     done() 
    }) 
    }) 

作品期待して通過すると::簡単な例として

expect(err.status).toBe(200) // This should fail 

次にテスト:

Messages 
    ✓ [MESSAGES-1] cannot be posted without an auth token 

しかし私は別のステータスコードを期待する私の主張を変更した場合タイムアウトで失敗します!

1) Messages [MESSAGES-1] cannot be posted without an auth token: 
    Error: timeout of 1000ms exceeded. Ensure the done() callback is being called in this test. 

これはよくある問題ですか?回避策や調整がありますか?私は約束を使う能力を失いたくはありません。

答えて

2

これは既知の問題ですか?

これは実際問題ではありません。

expect(err.status).toBe(200)は、.thenの内部で飲み込まれたエラーをスローし、コードが決してdone()に届かないという問題があります。あなたがキャッチ

it('[MESSAGES-1] cannot be posted without an auth token', function(done) { 
    agent.post(config.webRoot + '/rooms/ABC/messages').send({ 
     content: 'This is a test!' 
    }).end() 

    .then(function(res) { 
     // Not expected 
    }, function(err) { 
     expect(err.status).toBe(401) 
     done() 
    }) 
    .catch(function(err) { 
     done(err); //report error thrown in .then 
    }) 
    }) 

このようにしてexpect(err.status).toBe(200)によってスローされたエラーを報告する:あなたは、次のあなたのコードを再構築する必要があります。

+0

それでした!私はJavaScriptで約束したことを初めて知った - 私は 'catch()'を認識していなかったが、それは完全に機能する。 –

2

あなたのケースでは、http要求が失敗したか、または期待が失敗してアサーションエラーがスローされたために、完了コールバックが呼び出されないためにタイムアウトが発生します。

モカは適切な(約束の返す)非同期テストを処理するので、完了したコールバックを使用しないで、約束を混ぜると混乱が生じます。代わりに約束を返してください:

it('[MESSAGES-1] cannot be posted without an auth token', function() { 
    return agent.post(config.webRoot + '/rooms/ABC/messages').send({ 
    content: 'This is a test!' 
    }).end().then(function(res) { 
    // here you must throw an error, because if the post didnt fail somehow, the test would be green because of no assertations and no promise rejection. 
    throw new Error("Not expected"); 
    }, function(err) { 
    expect(err.status).toBe(401); 
    }); 
}); 
+0

"* ... http要求が失敗したため... *" OPは明示的に彼がコードに対して行う変更は 'expect(err.status).toBe(401)'を 'expect(err .status).toBe(200) 'となります。この前提に基づいて問題は、スローされたアサーションエラーが '.then'約束の中のコードの実行を停止することです.OPのコードが約束によって呑み込まれるエラーです。 – rabbitco

+0

@rabbitcoだから、約束をするときに 'done'を使うべきではないし、モカがそれらを適切に扱わせるようにすべきなのです。 – robertklep

+0

@robertklep:agree – rabbitco

関連する問題