In the last months I've been working with JavaScript and using SinonJS to stub some behaviours. I've manage to make it work, I've stubbed lots of methods and everything works great.
But I still have some questions about how Sinon works under the table. I guess I'm saying Sinon, but this question might apply to every other library designed to mock/stub/spy.
The language I've worked most in the past years was Java. 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.
When I first start working with SinonJS, I saw something like this:
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)
And it works. When we run the tests, the request
inside the implementation moduleUnderTest.js
calls the stubbed version of request
module.
My question is: why this works?
When the test calls the implementation execution, the implementation requires and uses the request
module. 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)? 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?
I've tried to follow the logic in stub.js
code in Sinon repo, but I'm not very familiar with JavaScript yet.
Sorry the long post and sorry if this is a dummy question. :)