簡體   English   中英

是否可以使用 sinon 在 CommonJS 模塊中對導出的 function 進行存根?

[英]Is it possible to stub an exported function in a CommonJS module using sinon?

快到 2021 年,有沒有辦法模擬單個 function? 我的意思是 function 沒有 object。

// demo.js
module.exports = () => {
  return 'real func demo';
};

// demo.test.js
const demo = require("./demo");
// ...
sinon.stub(demo).callsFake(() => {
  return 'mocked function';
});
expect(demo()).to.eq('mocked function')

您可以使用as語法導入。

如果您導出為default ,則使用“默認值”而不是實際名稱

import * as yourModule from '../<path>';
    
const fake = sinon.fake.returns(<value>);
sinon.replace(yourModule, 'default', fake);

我將在這里引用自己

您不能在 ES2015 兼容模塊 (ESM) 和 Node.js 中的 CommonJS 模塊中存根獨立導出的函數。 這就是這些模塊系統的工作方式。 只有在將它們轉化為其他東西之后,才能實現您想要的。 如何替換模塊完全是特定於環境的,這就是為什么 Sinon 將自己吹捧為“JavaScript 的獨立測試間諜、存根和模擬”而不是模塊替換工具的原因,因為最好留給特定於環境的實用程序(代理、各種 webpack 加載程序、Jest等),無論您身處何種環境。

要更深入地了解為什么在使用解構時在 CommonJS 中永遠不起作用,請參閱我的答案。 您需要注入一個攔截加載的模塊加載器。

這就是在符合規范的環境中嘗試使用 Sinon 存根 ESM 模塊的情況:

$ node esm-stubbing.mjs
/private/tmp/test/node_modules/sinon/lib/sinon/stub.js:72
        throw new TypeError("ES Modules cannot be stubbed");
              ^

TypeError: ES Modules cannot be stubbed
    at Function.stub (/private/tmp/test/node_modules/sinon/lib/sinon/stub.js:72:15)
    at Sandbox.stub (/private/tmp/test/node_modules/sinon/lib/sinon/sandbox.js:388:37)
    at file:///private/tmp/test/esm-stubbing.mjs:4:7

$ cat esm-stubbing.mjs
import sinon from "sinon";
import * as myModule from "./module.mjs";

sinon.stub(myModule, "foo").returns(42);

這只是 Sinon 自己在看到模塊的命名空間是只讀的時候拋出了一個錯誤,而不是讓 Node 拋出一個更神秘的錯誤信息。

暫無
暫無

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

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