【问题标题】:node - using jest with esm packagenode - 将 jest 与 esm 包一起使用
【发布时间】:2018-11-01 04:25:43
【问题描述】:

我想知道如何将 esmhttps://www.npmjs.com/package/esm 与 jest 合并到节点后端。

我尝试在文件的最顶部设置带有require("esm")require("esm")(module) 的设置文件,但它仍然给我SyntaxError: Unexpected token 错误。

我之前会使用node -r esm,但 jest 不支持这个。

【问题讨论】:

    标签: javascript jestjs


    【解决方案1】:

    当您执行require("esm")(module) 时,可以将其想象为您正在创建一个等待将文件转换为 ES 模块的 esm-transformer 函数。

    这是我对节点 v8+ 的尝试:

    • 默认jest配置

    • 默认esm配置

    utils-1.js:

    export const add = (a, b) => a + b;
    

    utils-2.js:

    export const multiAdd = array => array.reduce((sum, next) => sum + next, 0)
    

    _test_/utils-1.assert.js

    import { add } from '../utils-1';
    
    describe('add(a,b)', () => {
      it('should return the addtion of its two inputs', () => {
        expect(add(1,2)).toBe(3);
      });
    });
    

    _test_/utils-2.assert.js

    import { multiAdd } from '../utils-2';
    
    describe('multiAdd(<Number[]>)', () => {
      it('should return a summation of all array elements', () => {
        expect(multiAdd([1,2,3,4])).toBe(10);
      })
    });
    

    _test_/utils.test.js

    const esmImport = require('esm')(module);
    const utils_1 = esmImport('./utils-1.assert')
    const utils_2 = esmImport('./utils-2.assert')
    

    希望这会有所帮助!

    【讨论】:

    • 这对我来说比文档更有意义。
    • 其实multiAdd可以简单的array.reduce(add,0)
    • 我已经这样做了,但由于某种原因我失去了 jest 变量,所以我不能做 jest.spyOn 例如
    • 什么?在此示例中,您甚至没有使用 esm 包。这是一个公认的答案吗?
    • @AndrewKoster - 正在使用 esm 模块,但像这样:const esmImport = require('esm')(module);
    猜你喜欢
    • 2021-10-27
    • 2021-08-08
    • 2018-02-08
    • 1970-01-01
    • 2017-10-31
    • 2018-04-04
    • 2018-08-09
    • 2017-12-02
    • 2019-11-26
    相关资源
    最近更新 更多