jhnns / rewire

Easy monkey-patching for node.js unit tests
MIT License
3.08k stars 128 forks source link

rewiring any function executes every line that isn't in any function #183

Open leopuzzuoli opened 4 years ago

leopuzzuoli commented 4 years ago

My goal is to unit test the following Node.js script (heavily simplified for readability):

script.js

//setup
console.log("dosomething");
callfunction();

//functions
function callfunction(){
return "function called";
}

with the following mocha / chai test:

/test/test_script.js

let assert = require("assert");

describe("script", () => {
  it("should equal function called", () => {
    assert(callfunction() === "function called");    
 })
})

This obviously doesn't work as callfunction() is not recognized. So i tried using the module "rewire" to obtain the function:

let assert = require("assert");
let rewire = require("rewire"); //tonguetwister right there
let path = require("path");

describe("script", () => {
  it("should equal function called", () => {
    let app = rewire(path.resolve("script.js"));
    callfunction = app.__get__("callfunction");
    assert(callfunction() === "function called");
 })
})

This however, instead of just executing callfunction(), executes the entire script, including the initial console.log("dosomething").