Mock config file on a test by test basis

Viewed 15

I have a banking app which has a function

transferFunds(sender,recipient,amount)

which takes a source account, destination account and an amount of dollars.
Theres a also a config file with a setting called overDrawAllowed which if set to true allows customers to transfer more money than they have with their accounts just becoming negative.

This behaviour is tested in 2 unit tests:

 test1.spec.js
 function testTransferOverdraw(){
      //new account with 100$
     let acc1=newAccount(100)
     let acc2=newAccount(0)

     transfer(acc1,acc2,200)
     assert(getAccountBalance(acc1)===-100)
     assert(getAccountBalance(acc2)===200)

}





test2.spec.js
function testTransferNoOverdraw(){
      //new account with 100$
     let acc1=newAccount(100)
     let acc2=newAccount(0)

     try{
       transfer(acc1,acc2,200)
       assert(false)
     }catch(e){}

}

now the problem is there is no way for both tests to pass with the same json config file. And so i basically need a way to change the config file on the file for a given test file (i currently use mocha, if that is relevant).
I tried proxyquire, but that only changes the config file for a single given js module instead of globally. I also thought about using node-config or dotenv, but that can only change it for a given NODE_ENV. So how can I change the config file on the fly?

1 Answers

I have found out you can just set the config variable since its cached between all modules:

 test1.spec.js
 const config=require("../config.json")
 function testTransferOverdraw(){
      let lastSetting=config.allowOverdraw
      config.allowOverdraw=true
      //new account with 100$
     let acc1=newAccount(100)
     let acc2=newAccount(0)

     transfer(acc1,acc2,200)
     assert(getAccountBalance(acc1)===-100)
     assert(getAccountBalance(acc2)===200)

     config.allowOverdraw=lastSetting
}





test2.spec.js
 const config=require("../config.json")
function testTransferNoOverdraw(){
      let lastSetting=config.allowOverdraw
      config.allowOverdraw=false

      //new account with 100$
     let acc1=newAccount(100)
     let acc2=newAccount(0)

     try{
       transfer(acc1,acc2,200)
       assert(false)
     }catch(e){}         
     config.allowOverdraw=lastSetting

}
Related