1

So, I was doing some testing with Rewire with Mocha, and I noticed behavior that seems odd to me. using myModule.__set__() seems to actually set the specified variable in the the specified module (myModule), AND in the global scope of the current module (the one that ran the __set__()). For example:

This code runs after running mocha test:

Test.js:

var rewire = require("rewire")
var sinon = require("sinon")
var test2 = rewire("./test2.js")
var expect = require("chai").expect

var spy = sinon.spy()


describe("test", function () {
    beforeEach(function () {
        test2.__set__("console", { log: spy })
    })
    it("test should be equal to 3", function () {
        test2.test1()
        console.log("testing5")
        expect(spy.callCount).to.equal(3)
    })
})

Test2.js:

module.exports = {
  test1() {
      console.log("test")
      console.log("test")
      console.log("test")
  }
}

Here, I would expect "testing5" to actually be logged to the console, but the 3 "test"s to just be recorded in the spy, and the callCount to be equal to 3. This is not what is happening however. The "testing5" is not being logged, but is being recorded to that sinon spy, and the test is failing, because the callCount is 4, and not 3. To me this doesn't seem like this would be intended. Is there something I'm doing wrong?

0 Answers0