Skip to content

Instantly share code, notes, and snippets.

@andrejewski
Created October 7, 2018 17:59
Show Gist options
  • Save andrejewski/43210daa108dcbfb925d3db6c2d0e4c9 to your computer and use it in GitHub Desktop.
Save andrejewski/43210daa108dcbfb925d3db6c2d0e4c9 to your computer and use it in GitHub Desktop.
Playing with a new kind of mock/stub/spy
function withTest (service, tester) {
function mark () {
if (process.env.NODE_ENV !== 'test') {
return service
}
}
return { ...service, mark, testMark }
}
function createTester () {
const service = {}
const inspector = {}
return { service, inspector }
}
function sock ({ isEnabled }) {
const keyServiceDict = {}
const keyTesterDict = {}
const keyStockDict = {}
const serviceTesters = new Map()
return {
register (service, tester) {
serviceTesters.set(service, tester)
},
mark (service, key) {
if (!isEnabled) {
return service
}
keyServiceDict[key] = service
return createProxy(service, () => {
const tester = keyTesterDict[key]
return tester && tester.service
})
},
test (key) {
const service = keyServiceDict[key]
const createTester = serviceTesters.get(service)
function dispose () {
keyStockDict[key] = Math.max(0, (keyStockDict[key] || 0) - 1)
if (!keyStockDict) {
}
}
/*
The issue with this interweaving approach is that multiple tests could be using the same sock.
Thus making it impossible to reliably decide which tester is working with the code at a given time.
We can't provide enough information do the code side to know how to switch.
It seems DI with a Service and TestService (with inspection) is going to be the best solution.
*/
return { tester, dispose }
}
}
}
/*
// In the code:
const blobService = require('back/blob').blobService.mark('abc')
// In the test:
it('should', t => {
const blobTester = require('back/blob').blobService.testMark('abc')
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment