使用带有 sinon.js 的 ES 模块时如何存根常量函数? [英] How to stub constant functions when using ES Modules with sinon.js?

查看:31
本文介绍了使用带有 sinon.js 的 ES 模块时如何存根常量函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 ES 模块,我们将一些导出函数定义为 const,这通常是标准做法.然而,在单元测试期间,这些 const 函数不能被剔除,从单元测试的角度来看这似乎是有问题的.例如,

With ES Modules, we define some exported functions as const and it is often a standard practice. However, during unit testing, these const functions can't be stubbed out which seems problematic from a unit testing perspective. For example,

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 代码不起作用:

Now to unit test readJson, I would typically want to stub readFile$ function. Unfortunately, following Sinon code doesn't work:

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

由于Sinon只是简单地改变了引用myFs.readFile$,原来的const仍然指向原来的函数,而后者又被readJson调用功能.

Since Sinon is simply changing reference myFs.readFile$, original const still points to the original function which is in turn called by readJson function.

任何建议 - 我怎样才能在同一个模块中真正存根/模拟常量函数?

推荐答案

const 是常量,不能使用普通"代码更改它.不幸的是 sinon 不是魔术.您需要检测您的代码以允许更改常量值.

const is constant one can't change it using "normal" code. Unfortunately sinon is not magic. You need to instrument your code to allow changing constant value.

假设您使用 babel 进行转译,您可以使用 babel-plugin-重新接线.

Assuming you are using babel to transpile you could use babel-plugin-rewire.

将其添加到您的 babel 配置后,您将能够在测试代码中执行以下注入

After adding it to your babel config you would be able to do the following injection in your test code

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.js 的 ES 模块时如何存根常量函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆