簡體   English   中英

使用 sinon 的存根方法

[英]Stubbing method using sinon

我試圖在 sinon 中存根一個方法。

這是一個簡化的例子

function a() {
    return b().add(1, 'days');
}

function b() {
   return moment.utc();
}

module.exports = {
  a: a,
  b: b
};

我想存根 function b()以在從需要它的文件(例如theFile.b() )調用時返回特定的時刻日期,並且在調用方法a()時它也應該在內部進行模擬。

我試過以下

  sinon.stub(theFile, 'b').callsFake(function() {
    console.log("Calling mocked sinon ")
    return moment("2021-10-10", 'YYYY-MM-DD').utc().startOf('day');
  });

在外部調用時有效,但在 function a()內部調用時無效。

我可以看到這是因為 sinon 覆蓋了模塊導出,但必須有辦法解決這個問題。 有人可以幫忙嗎?


更新

我試過使用 fakeTimers

function setMoockMomentDate(formattedDate) {
  const mockTimestamp =moment.utc(formattedDate, "YYYY-MM-DD").valueOf();
  console.log("Setting sinon to use " + mockTimestamp);
  const clock = sinon.useFakeTimers(mockTimestamp);
  clock.runAll();
}

它在測試開始時被調用。

它調用的第一個 function 在我的 Firestore 模擬數據庫中異步更新某些內容

由於時鍾變化,這些似乎掛起。

我看到的每個示例都涉及使用具有預定義時間段的 setTimeout 來等待例如 1000 毫秒,在我的情況下我沒有。 例如

    console.log("Setting the fake date");
    setMoockMomentDate(startDateMocked);
    console.log("set the fake date");
    console.log(1)
    await testVariablesFile.func.updateFirestoreDoc(uid, {newKey: 'newVal'});
    console.log(2)


...
// other file

async function updateHasPhoto(uid, newVal) {
  const userDocRef = firestore.doc('users/' + uid);
  console.log("Starting update");
  await userDocRef.update(newVal);
  console.log("Finished update");
}

有沒有一種簡單的方法,只需 mocking 系統時間而不失信?

您可以這樣使用:在原始文件和測試文件中對 function b保持相同的引用。

index.js

const moment = require('moment');

function a() {
  return exports.b().add(1, 'days');
}

function b() {
  return moment.utc();
}

exports.a = a;
exports.b = b;

index.test.js

const theFile = require('./');
const moment = require('moment');
const sinon = require('sinon');

describe('65081463', () => {
  it('should pass', () => {
    sinon.stub(theFile, 'b').callsFake(function() {
      console.log('Calling mocked sinon ');
      return moment('2021-10-10', 'YYYY-MM-DD')
        .utc()
        .startOf('day');
    });
    const actual = theFile.a();
    console.log(actual);
  });
});

測試結果:

  65081463
Calling mocked sinon 
Sun Oct 10 2021 00:00:00 GMT+0000
    ✓ should pass


  1 passing (12ms)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM