无法使用 Sinon 存根导出的函数

Unable to stub an exported function with Sinon

我需要测试以下 createFacebookAdVideoFromUrl(),它消耗了我想用 Sinon 存根的 retryAsyncCall

async function createFacebookAdVideoFromUrl(accountId, videoUrl, title, facebookToken = FACEBOOK_TOKEN, options = null, businessId = null) {
  const method = 'POST';
  const url = `${FACEBOOK_URL}${adsSdk.FacebookAdsApi.VERSION}/${accountId}/advideos`;

  const formData = {
    access_token: businessId ? getFacebookConfig(businessId).token : facebookToken,
    title,
    name: title,
    file_url: videoUrl,
  };

  const callback = () => requestPromise({ method, url, formData });

  const name = 'createFacebookAdVideoFromUrl';
  const retryCallParameters = buildRetryCallParameters(name, options);

  const adVideo = await retryAsyncCall(callback, retryCallParameters);

  logger.info('ADVIDEO', adVideo);

  return { id: JSON.parse(adVideo).id, title };
}

retryAsyncCall 函数导出为:

module.exports.retryAsyncCall = async (callback, retryCallParameters, noRetryFor = [], customRetryCondition = null) => {
 // Implementation details ...
}

到目前为止,我是这样编写测试的:

it.only("should create the video calling business's Facebook ids", async () => {
        const payload = createPayloadDataBuilder({
          businessId: faker.internet.url(),
        });

        const retryAsyncCallStub = sinon.stub(retryAsyncCallModule, 'retryAsyncCall').resolves('random');

        const createdFacebookAd = await FacebookGateway.createFacebookAdVideoFromUrl(
          payload.accountId,
          payload.videoUrl,
          payload.title,
          payload.facebookToken,
          payload.options,
          payload.businessId,
        );

        assert.strictEqual(retryAsyncCallStub.calledOnce, true);
        assert.strictEqual(createdFacebookAd, { id: 'asdf', title: 'asdf' });
      });

我不希望它立即工作,因为我正在以 TDD 方式工作,但我确实希望 retryAsyncCall 被删除。然而,我仍然遇到来自 mocha 的 TypeError: Cannot read property 'inc' of undefined 错误,它指的是 retryAsyncCall.

的内部函数

如何使 sinon 存根工作?

我通过更改在我的 SUT 中导入的方式修复了它:

// from 
const { retryAsyncCall } = require('../../../helpers/retry-async');
// to
const retry = require('../../../helpers/retry-async');

在我的测试文件中:

// from 
import * as retryAsyncCallModule from '../../../src/common/helpers/retry-async';
// to
import retryAsyncCallModule from '../../../src/common/helpers/retry-async';

解构的使用似乎是复制而不是使用相同的引用,因此存根没有应用到正确的引用上。