1

テスト対象の関数は、おおよそ次のようになります。

  function doThing(data, callback) {

    externalService.post('send').request(data)
        .then(() => {
          if (callback) { callback(); }
        })
        .catch((message) => {
          logger.warn('warning message');
          if (callback) { callback(); }
        });
  }

Chai と Sinon を使用してこれをテストしようとしています。

さまざまなガイドに従ってみましたが、現在の呪文は次のようになります。

const thingBeingTested = require('thing-being-tested');
const chai = require('chai');
const sinon = require('sinon');
require('sinon-as-promised');
const sinonChai = require('sinon-chai');
const expect = chai.expect;

var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
chai.use(sinonChai);

describe('The Thing', () => {  
  it('should run a callback when requested and successful', done => {

    const externalService = { post: { request: sinon.stub() } };
    const callback = sinon.spy();

    externalService.post.request.resolves(callback);

    doThing({...}, callback);
    expect(callback).to.have.been.called;
    done();
  });
});

externalService.post正しくスタブアウトできません。どんな助けでも大歓迎です。

私は Chai と Sinon にまったく慣れていないので、ばかげたことをしていることを十分に期待してください。

4

1 に答える 1

1

関数はテストからdoThingアクセスできません。const externalServiceあなたのメインファイルには次のようなものがあると仮定します

const externalService = require('./external_service');

それを得るために。

テストでも同じ結果が得られるはずですexternalService

describe(..., () => {
    it(..., () => {
        // adjust the path accordingly
        const externalService = require('./external_service');

次に、そのメソッドをモックします。

sinon.stub(externalService, 'post').returns({
    request: sinon.stub().resolves(callback)
});

doThing次に、結果を呼び出して分析できます。

postテストが完了したら、元に戻すことを忘れないでください。

externalService.post.restore();
于 2016-10-12T11:18:04.857 に答える