gpt4 book ai didi

javascript - Sinon stub 是如何工作的?

转载 作者:数据小太阳 更新时间:2023-10-29 05:07:07 26 4
gpt4 key购买 nike

在过去的几个月里,我一直在使用 JavaScript 并使用 SinonJS 来 stub 一些行为。我已经设法让它发挥作用,我使用了很多方法,一切都很好。

但对于诗浓在幕后的运作方式,我还是有些疑问。我想我说的是 Sinon,但这个问题可能适用于所有其他旨在模拟/ stub / spy 的库。

过去几年我使用最多的语言是 Java。在 Java 中,我使用 Mockito 来模拟/ stub 依赖项和依赖项注入(inject)。我曾经导入类,用 @Mock 注释字段并将此模拟作为参数传递给被测类。我很容易看出我在做什么:模拟一个类并将模拟作为参数传递。

当我第一次开始使用 SinonJS 时,我看到了这样的东西:

moduleUnderTest.spec.js

const request = require('request')

describe('Some tests', () => {
let requestStub

beforeEach(() => {
requestStub = sinon.stub(request, 'get')
})

afterEach(() => {
request.get.restore()
})

it('A test case', (done) => {
const err = undefined
const res = { statusCode: 200 }
const body = undefined
requestStub
.withArgs("some_url")
.yields(err, res, body)

const moduleUnderTest = moduleUnderTest.someFunction()

// some assertions
})
})

moduleUnderTest.js

const request = require('request')
// some code
request
.get("some_url", requestParams, onResponse)

而且它有效。当我们运行测试时,moduleUnderTest.js 实现中的 request 调用 request 模块的 stub 版本。

我的问题是:为什么会这样?

当测试调用实现执行时,实现需要并使用request模块。如果我们不将 stub 对象作为参数传递(注入(inject)),Sinon(和其他模拟/ stub / spy 库)如何设法使实现调用 stub ? Sinon 在测试执行期间替换了整个 request 模块(或其中的一部分),通过 require('request') 使 stub 可用,然后在测试完成后恢复它完成了吗?

我试图遵循 stub.js 中的逻辑Sinon repo 中的代码,但我对 JavaScript 还不是很熟悉。对不起,很长的帖子,如果这是一个虚拟问题,我很抱歉。 :)

最佳答案

How Sinon (and other mock/stub/spy libraries) manage to make the implementation call the stub if we are not passing the stubbed object as param (injecting it)?

让我们编写自己的简单 stub 工具,好吗?

为简洁起见,它非常有限,不提供 stub API,并且每次只返回 42。但这应该足以说明 Sinon 是如何工作的。

function stub(obj, methodName) {
// Get a reference to the original method by accessing
// the property in obj named by methodName.
var originalMethod = obj[methodName];

// This is actually called on obj.methodName();
function replacement() {
// Always returns this value
return 42;

// Note that in this scope, we are able to call the
// orignal method too, so that we'd be able to
// provide callThrough();
}

// Remember reference to the original method to be able
// to unstub (this is *one*, actually a little bit dirty
// way to reference the original function)
replacement.originalMethod = originalMethod;

// Assign the property named by methodName to obj to
// replace the method with the stub replacement
obj[methodName] = replacement;

return {
// Provide the stub API here
};
}

// We want to stub bar() away
var foo = {
bar: function(x) { return x * 2; }
};

function underTest(x) {
return foo.bar(x);
}

stub(foo, "bar");
// bar is now the function "replacement"
// foo.bar.originalMethod references the original method

underTest(3);

Sinon replaces the whole request module (or part of it) during the test execution, making the stub available via require('request') and then restore it after the tests are finished?

require('request') 每次调用时都会返回在“request”模块中创建的相同(对象)引用。

参见 NodeJS documentation :

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

如果还不清楚:它只替换从“请求”模块返回的对象引用的单个方法,它不替换模块。

这就是你不打电话的原因

stub(obj.method)

因为这只会传递对函数 method 的引用。 Sinon 将无法更改对象obj

文档进一步说:

If you want to have a module execute code multiple times, then export a function, and call that function.

这意味着,如果一个模块看起来像这样:

foo.js

module.exports = function() {
return {
// New object everytime the required "factory" is called
};
};

ma​​in.js

        // The function returned by require("foo") does not change
const moduleFactory = require("./foo"),
// This will change on every call
newFooEveryTime = moduleFactory();

此类模块工厂函数无法 stub ,因为您无法替换 require() 从模块内 导出的内容。


In Java, I've used Mockito to mock/stub the dependencies and dependency injection. I used to import the Class, annotate the field with @Mock and pass this mock as param to the class under test. It's easy to me to see what I'm doing: mocking a class and passing the mock as param.

在 Java 中,您(无)不能将方法重新分配给新值,这是无法做到的。取而代之的是生成新的字节码,使模拟提供与模拟类相同的接口(interface)。与 Sinon 相比,Mockito 的所有方法都被模拟并且应该是 explictly instructed。调用真正的方法。

Mockito 将有效调用 mock()最后将结果赋值给注解字段。

但是您仍然需要将 mock 替换/分配给被测类中的字段,或者将其传递给测试方法,因为 mock 本身没有帮助。

@Mock
Type field;

Type field = mock(Type.class)

其实相当于Sinons mocks

var myAPI = { method: function () {} };
var mock = sinon.mock(myAPI);

mock.expects("method").once().throws();

方法先replaced with the expects() call :

wrapMethod(this.object, method, function () {
return mockObject.invokeMethod(method, this, arguments);
});

关于javascript - Sinon stub 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44932261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com