Sinon 存根是如何工作的?

How Sinon stubs works under the hood?

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

但我对诗乃在table下的工作方式仍有一些疑问。我想我说的是 Sinon,但这个问题可能适用于为 mock/stub/spy.

设计的所有其他库

过去几年我工作最多的语言是Java。在 Java 中,我使用 Mockito mock/stub 依赖项和依赖项注入。我曾经导入 Class,用 @Mock 注释该字段,并将此模拟作为参数传递给正在测试的 class。我很容易看出我在做什么:模拟 class 并将模拟作为参数传递。

当我第一次开始使用 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 模块的存根版本。

我的问题是:为什么这有效?

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

我尝试遵循 Sinon 存储库中 stub.js 代码中的逻辑,但我对 JavaScript 还不是很熟悉。 很抱歉长post,如果这是一个虚拟问题,我很抱歉。 :)

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)?

让我们编写自己的简单存根实用程序,好吗?

为简洁起见,它非常有限,不提供存根 API 并且每次只提供 returns 42。但这应该足以说明诗乃的工作原理了。

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') 将 return 相同的(对象)引用,它是在 "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.

如果还不清楚:它仅替换了从 "requested" 模块编辑的对象引用 return 的单个方法,它不替换模块。

这就是你不打电话的原因

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
    };
};

main.js

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

无法存根此类模块工厂函数,因为您无法替换 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 中,您(无)不能将方法重新分配给新值,这是无法做到的。取而代之的是生成新的字节码,使模拟提供与模拟 class 相同的接口。与 Sinon 相比,Mockito 的所有方法都是模拟的,应该 explictly instructed 才能调用真正的方法。

Mockito 会有效地调用 mock() 并最终将结果分配给带注释的字段。

但是您仍然需要 replace/assign 模拟到 class 中的一个字段进行测试或将其传递给测试方法,因为该模拟本身就是没有帮助。

@Mock
Type field;

Type field = mock(Type.class)

实际上相当于诗乃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);
});