簡體   English   中英

使用帶有 sinon.js 的 ES 模塊時如何存根常量函數?

[英]How to stub constant functions when using ES Modules with sinon.js?

對於 ES 模塊,我們將一些導出函數定義為const ,這通常是標准做法。 然而,在單元測試期間,這些 const 函數不能被剔除,從單元測試的角度來看這似乎是有問題的。 例如,

import * as fs from 'fs';

import { bindNodeCallback } from 'rxjs';
import { map } from 'rxjs/operators';

// readFile :: string, string => Observable<string>
export const readFile$ = bindNodeCallback(fs.readFile);

// readJson :: string => Observable<any>
export function readJson(fileName) {
    return readFile$(fileName, 'utf-8')
        .pipe(map((rawFile) => JSON.parse(rawFile)));
}

現在要對 readJson 進行單元測試,我通常想要存根readFile$函數。 不幸的是,以下 Sinon 代碼不起作用:

// Setup data - stubs / mocks
const stub = sinon.stub(myFs, 'readFile$').returns(json$);

由於 Sinon 只是更改引用myFs.readFile$ ,因此原始const仍指向原始函數,該函數又由readJson函數調用。

任何建議 - 我如何才能在同一模塊中真正存根/模擬常量函數?

const是常量,不能使用“普通”代碼更改它。 不幸的是, sinon不是魔法。 您需要檢測您的代碼以允許更改常量值。

假設您使用 babel 進行轉譯,您可以使用babel-plugin-rewire rewire 。

將它添加到您的 babel 配置后,您將能夠在您的測試代碼中進行以下注入

import { default as readJson, __RewireAPI__ as rewire } from './path/to/readJson.js'

const stub = sinon.stub(myFs, 'readFile$').returns(json$)
rewire.__set__('readFile$', stub)

// readJson() would now call provided stub

我相信 Sinon 有辦法做到這一點,而無需使用第三方軟件包(例如 Babel)。 這是他們關於它的文檔頁面,有一個簡單的例子: How to stub a dependency of a module 我只是自己嘗試過,它似乎有效。

抱歉,我沒有時間在回復中在這里分享任何代碼。 我知道這是一種糟糕的形式:-/ 但希望該鏈接可以幫助某些人。

暫無
暫無

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

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