Thursday, 7 October 2021

sinon stubs best practises in ESM projects

I have spent so much time trying to have a reasonable understanding of this matter. Unfortunately, most of the questions are very specific to indivisual usecases and do not present a general guide to follow. Also could not find any straight answer in the docs.

The Matter:

I was simply trying to do this:

// helper.ts

import fs from 'fs';
import util from 'util'
const accessPromisfied = util.promisfy(fs.access);

async function access(path:string){
    try{
      
       await accessPromisfied(path);
       return true;
    } catch {
        return false;
    }      
}


 async function someFunction(){
    try{
      let result = await access()
      if(result){

      //some more logic here
       . 
       .
       return true;
     }
      
    }catch{
       return false;
    }
   
 }

 export default {access, someFunction}


// helper.spec.ts

import * as helper from './helper.ts';

describe("The test", () => {
   
 afterEach(() => {
    sinon.restore();
 })

 it("Should JUST work like we all wish", async () => {

    // stub acccess to resolve false
    const stubAccess = sinon.stub(helper, 'access').resolve(false);
    
    // rest of test code
 })

})

The Questions

  1. Is there any certain/only way to import local user-defiend modules?
  2. Why my test code seems to be not stubbing the function in question? What causes sinon to do that?

Finally, Please note that i am using nextjs, ESM in my project!!



from sinon stubs best practises in ESM projects

No comments:

Post a Comment