0

chai.expectアサーションが失敗すると、通常はテストに失敗し、否定的な結果がテスト ランナーのレポートに追加されます (この場合は) mocha

ただし、 を使用してラップされたジェネレーター関数を使用するco.wrap()と、以下に示すように、奇妙なことが起こります。アサーションがパスすると、すべてが正常に実行されます。ただし、アサーションが失敗すると、テストはタイムアウトします。

+coと一緒に使用するにはどうすればよいですか?mochachai


it('calls API and then verifies database contents', function(done) {
  var input = {
    id: 'foo',
    number: 123,
  };
  request
    .post('/foo')
    .send(input)
    .expect(201)
    .expect({
      id: input.id,
      number: input.number,
    })
    .end(function(err) {
      if (!!err) {
        return done(err);
      }

      // Now check that database contents are correct
      co.wrap(function *() {
        var dbFoo = yield foos.findOne({
          id: input.id,
        });
        continueTest(dbFoo);
      })();

      function continueTest(dbFoo) {
        //NOTE when these assertions fail, test times out
        expect(dbFoo).to.have.property('id').to.equal(input.id);
        expect(dbFoo).to.have.property('number').to.equal(input.number);
        done();
      }
    });
});

解決:

以下の@Bergiが指摘しているように、co.wrap()によってスローされた例外を飲み込み、それを見つけるexpect()ために必要な場所までバブルアップできないために問題が発生しました。mocha

co()解決策は、以下に示すように、代わりにを使用し、そのコールバックco.wrap()を追加.catch()して渡すことでした。done

      // Now check that database contents are correct
      co(function *() {
        var dbFoo = yield foos.findOne({
          id: input.id,
        });
        continueTest(dbFoo);
      }).catch(done);
4

2 に答える 2

2

co.wrapジェネレーターからの例外をキャッチし、返された promise を拒否します。のアサーションからスローされるエラーを「飲み込み」ますcontinueTest。ところで、それを使用してすぐに呼び出す代わりに、.wrap単に呼び出すことができますco(…)

co(function*() {
    …
}).then(done, done); // fulfills with undefined or rejects with error

また

co(function*() {
    …
    done();
}).catch(done);

ところで、co を適切に使用するには、すべての非同期関数を単一のジェネレーターに配置します。

it('calls API and then verifies database contents', function(done) {
  co(function*() {
    var input = {
      id: 'foo',
      number: 123,
    };
    yield request
      .post('/foo')
      .send(input)
      .expect(201)
      .expect({
        id: input.id,
        number: input.number,
      })
      .endAsync(); // assuming you've promisified it

    // Now check that database contents are correct
    var dbFoo = yield foos.findOne({
      id: input.id,
    });

    expect(dbFoo).to.have.property('id').to.equal(input.id);
    expect(dbFoo).to.have.property('number').to.equal(input.number);

  }).then(done, done);
});
于 2015-08-12T00:22:18.267 に答える