0

promise の一部として返される関数をテストしています。chai-as-promisedを使用しています。

関数が機能することをテストできますが、エラーが適切にスローされることをテストできません。

約束に関連する多くのコードを除外して、テストしようとしている関数:

// function that we're trying to test 
submitTest = (options) => {
  // missingParam is defined elsewhere. It works - the error is thrown if screenshot not passed
  if (missingParam(options.screenShot)) throw new Error('Missing parameter');

  return {};
}

私のテスト:

describe('SpectreClient()', function () {
  let client;

  before(() => client = SpectreClient('foo', 'bar', testEndpoint));
  // the client returns a function, submitTest(), as a part of a promise

  /* 
  omitting tests related to the client
  */

  describe('submitTest()', function () {
    let screenShot;
    before(() => {
      screenShot = fs.createReadStream(path.join(__dirname, '/support/test-card.png'));
    });

    // this test works - it passes as expected
    it('should return an object', () => {
      const submitTest = client.then((response) => {
        return response.submitTest({ screenShot });
      });
      return submitTest.should.eventually.to.be.a('object');
    });

    // this test does not work - the error is thrown before the test is evaluated
    it('it throws an error if not passed a screenshot', () => {
      const submitTest = client.then((response) => {
        return response.submitTest({});
      });

      return submitTest.should.eventually.throw(Error, /Missing parameter/);
    });       
  });
})

テストの出力 -

// console output
1 failing

1) SpectreClient() submitTest() it throws an error if not passed a screenshot:
   Error: Missing parameter

エラーが正しくスローされることをテストするにはどうすればよいですか? それがモカの問題なのか、約束されたものなのか、それとも約束されたチャイなのか、私にはわかりません。大変助かりました。

4

1 に答える 1

0

promise ハンドラー内で発生した例外は、promise の拒否に変換されます。submitTestへのコールバック内で実行されるclient.thenため、発生する例外は約束の拒否になります。

したがって、次のようにする必要があります。

return submitTest.should.be.rejectedWith(Error, /Missing parameter/)
于 2016-11-14T12:11:09.623 に答える