5

promise を返すメソッド呼び出しをテストしようとしていますが、問題があります。これは NodeJS コードであり、Mocha、Chai、および Sinon を使用してテストを実行しています。私が現在持っているテストは次のとおりです。

it('should execute promise\'s success callback', function() {
  var successSpy = sinon.spy();

  mySpies.executeQuery = sinon.stub(databaseConnection, 'execute').returns(q.resolve('[{"id":2}]'));

  databaseConnection.execute('SELECT 2 as id FROM Users ORDER BY RAND() LIMIT 1').then(successSpy, function(){});

  chai.expect(successSpy).to.be.calledOnce;

  databaseConnection.execute.restore();
});

ただし、このテストでは次のエラーが発生します。

AssertionError: expected spy to have been called exactly once, but it was called 0 times

プロミスを返すメソッドをテストする適切な方法は何ですか?

4

2 に答える 2

7

then() 呼び出しのハンドラーは、登録中には呼び出されません。現在のテスト スタックの外にある次のイベント ループ中にのみ呼び出されます。

完了ハンドラー内からチェックを実行し、非同期コードが完了したことを mocha に通知する必要があります。http://visionmedia.github.io/mocha/#asynchronous-codeも参照してください。

次のようになります。

it('should execute promise\'s success callback', function(done) {
  mySpies.executeQuery = sinon.stub(databaseConnection, 'execute').returns(q.resolve('[{"id":2}]'));

  databaseConnection.execute('SELECT 2 as id FROM Users ORDER BY RAND() LIMIT 1').then(function(result){
    chai.expect(result).to.be.equal('[{"id":2}]');
    databaseConnection.execute.restore();
    done();
  }, function(err) {
    done(err);
  });
});

元のコードへの変更:

  • テスト関数の done パラメータ
  • then() ハンドラ内のチェックとクリーンアップ

編集: また、正直に言うと、このテストはコードに関して何もテストしていません。コードの唯一の部分 (databaseConnection) がスタブ化されているため、promise の機能を検証しているだけです。

于 2013-09-03T13:45:47.940 に答える