Last active
January 10, 2018 11:09
-
-
Save sdenier/fe94bb8c5ccd71dc6fe6f19f49d9ab73 to your computer and use it in GitHub Desktop.
Do not destructure module import in node if you want to spy on them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { resolve } = require("path"); | |
function joinPath(root, path) { | |
// resolve is the reference at load time, so not wrapped by the spy | |
return resolve(root, path); | |
} | |
module.exports = absolutePath; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require("path"); | |
function joinPath(root, path) { | |
// resolve is a reference to the spy installed by the beforeEach hook | |
return path.resolve(root, path); | |
} | |
module.exports = absolutePath; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const chai = require("chai"); | |
const path = require("path"); | |
const sinon = require("sinon"); | |
const sinonChai = require("sinon-chai"); | |
const { expect } = chai; | |
chai.use(sinonChai); | |
const module1 = require("./module_1"); | |
const module2 = require("./module_2"); | |
describe("Modules", () => { | |
let resolveSpy; | |
beforeEach(() => { | |
resolveSpy = sinon.spy(path, "resolve"); | |
}); | |
afterEach(() => { | |
path.resolve.restore(); | |
}); | |
it("calls path.resolve", () => { | |
module1.absolutePath('/home', 'home'); | |
expect(resolveSpy).to.be.called; | |
// Test fails because module1 calls the direct reference to resolve in path | |
}); | |
it("calls path.resolve", () => { | |
module2.absolutePath('/home', 'home'); | |
expect(resolveSpy).to.be.called; | |
// Test passes because module2 calls the spy installed on resolve in path | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment