【发布时间】:2022-01-27 05:35:49
【问题描述】:
我的代码如下:
// example.js
export function doSomething() {
if (!testForConditionA()) {
return;
}
performATask();
}
export function testForConditionA() {
// tests for something and returns true/false
// let's say this function hits a service or a database and can't be run in tests
...
}
export function performATask() {
...
}
// example.test.js
import * as example from 'example';
it('validates performATask() runs when testForConditionA() is true', () => {
const testForConditionAStub = sinon.stub(example, 'testForConditionA').returns(true);
const performATaskSpy = sinon.stub(example, 'performATask');
example.doSomething();
expect(performATaskSpy.called).to.equal(true);
});
(我知道,这是一个人为的例子,但我尽量保持简短)
我还没有找到使用 Sinon 模拟 testForConditionA() 的方法。
我知道有一些变通办法,比如
A) 将 example.js 中的所有内容放入一个类中,然后可以对类的函数进行存根。
B) 将 testForConditionA() (和其他依赖项)从 example.js 中移出到一个新文件中,然后使用 proxyquire
C) 将依赖项注入 doSomething()
但是,这些选项都不可行 - 我在一个大型代码库中工作,许多文件需要重写和大修。我已经搜索过这个主题,我看到了其他几篇文章,比如Stubbing method in same file using Sinon,但是除了将代码重构到一个单独的类(或一个人建议的工厂),或者重构到一个单独的文件并使用 proxyquire,我还没有找到解决方案。我以前使用过其他的测试和模拟库,所以很奇怪Sinon 不能做到这一点。或者是吗?关于如何在不重构要测试的代码的情况下对函数进行存根的任何建议?
【问题讨论】:
-
嗨,杰夫。如果我的回答在某些方面有帮助,请不要忘记点赞按钮或“接受回答”复选标记 ;)
-
您还有没有回答的问题?
标签: javascript unit-testing sinon