代码之家  ›  专栏  ›  技术社区  ›  Matías Fidemraizer

如何在nodejs中模拟es模块?

  •  2
  • Matías Fidemraizer  · 技术社区  · 6 年前

    假设我实现了一个模块,如下所示:

    import { foo } from 'dep1'
    
    export const bar = () => foo()
    

    我怎么嘲笑 dep1 所以我可以单元测试 bar 是吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Matías Fidemraizer    6 年前

    一种可能的方法是使用es模块加载程序挂钩。

    这么说吧 dep1 包含工作代码,我们要模拟它。我会创建一个名为 mymodule.mocks.mjs 我会嘲笑的地方 foo 以下内容:

    // Regular mymodule.mjs
    import { foo } from 'dep1'
    
    export const bar = () => foo()
    

    // Mocked mymodule.mocks.mjs
    
    // dep1.foo() returns string
    export const bar = () => 'whatever'
    

    现在我们应该可以装载 mymodule.mocks.mjs模块 什么时候? mymodule.mjs 在测试运行期间被请求。

    所以我们实施 testModuleLoader.mjs

    下面是一个自定义模块加载程序钩子,它实现了 *.mocks.mjs 惯例:

    import { existsSync } from 'fs'
    import { dirname, extname, basename, join } from 'path'
    import { parse } from 'url'
    
    // The 'specifier' is the name or path that we provide
    // when we import a module (i.e. import { x } from '[[specifier]]')
    export function resolve (
       specifier,
       parentModuleURL,
       defaultResolver
    ) {
       // For built-ins
       if ( !parentModuleURL )
          return defaultResolver ( specifier, parentModuleURL )
    
       // If the specifier has no extension we provide the
       // Michael Jackson extension as the default one
       const moduleExt = extname ( specifier ) || '.mjs'
       const moduleDir = dirname ( specifier )
       const { pathname: parentModulePath } = parse (
          parentModuleURL
       )
       const fileName = basename ( specifier, moduleExt )
    
       // We build the possible mocks' module file path
       const mockFilePath = join (
          dirname ( parentModulePath ),
          moduleDir,
          `${fileName}.mocks${moduleExt}`
       )
    
       // If there's a file which ends with '.mocks.mjs'
       // we resolve that module instead of the regular one
       if ( existsSync ( mockFilePath ) )
          return defaultResolver ( mockFilePath, parentModuleURL )
    
       return defaultResolver ( specifier, parentModuleURL )
    }
    

    使用它

    只不过是提供给 node 以下内容:

    node --experimental-modules --loader ./path/to/testModuleLoader.mjs ./path/to/app.mjs
    

    Learn more 关于ES模块加载程序挂钩。