对于 ES 模块,我们将一些导出函数定义为 const
,这通常是一种标准做法。但是,在单元测试期间,这些 const 函数不能被删除,从单元测试的 Angular 来看这似乎是有问题的。例如,
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 进行单元测试,我通常想要 stub readFile$
函数。不幸的是,以下 Sinon 代码不起作用:
// Setup data - stubs / mocks
const stub = sinon.stub(myFs, 'readFile$').returns(json$);
由于 Sinon 只是更改引用 myFs.readFile$
,原始 const
仍指向原始函数,该函数又由 readJson
调用功能。
任何建议 - 我怎样才能在同一个模块中真正 stub /模拟常量函数?
最佳答案
const
是常量,无法使用“普通”代码更改它。不幸的是 sinon
并不是魔法。您需要检测您的代码以允许更改常量值。
假设您正在使用 babel 进行转译,您可以使用 babel-plugin-rewire
.
将其添加到您的 babel 配置后,您将能够在您的测试代码中执行以下注入(inject)
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
关于javascript - 在 sinon.js 中使用 ES 模块时如何 stub 常量函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50460750/