sinon 存根 ESM 项目中的最佳实践

mus*_*afa 5 javascript mocha.js node.js sinon next.js

我花了很多时间试图对这件事有一个合理的理解。不幸的是,大多数问题都是针对具体用例的,并且没有提供可遵循的一般指南。在文档中也找不到任何直接答案。

事情的经过:

我只是想这样做:

// 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
 })

})
Run Code Online (Sandbox Code Playgroud)

问题

  1. 有没有特定/唯一的方法来导入本地用户自定义模块?
  2. 为什么我的测试代码似乎没有存根有问题的函数?到底是什么原因导致诗乃这么做呢?

最后,请注意,我在我的项目中使用了 nextjs、ESM!