Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 用Jest测试ES6模块_Unit Testing_Ecmascript 6_Jestjs_Es6 Modules - Fatal编程技术网

Unit testing 用Jest测试ES6模块

Unit testing 用Jest测试ES6模块,unit-testing,ecmascript-6,jestjs,es6-modules,Unit Testing,Ecmascript 6,Jestjs,Es6 Modules,如何使用Jest测试ES6模块 例如: sum.js module.exports = { presets: [ [ '@babel/preset-env', { targets: { node: 'current', }, }, ], '@babel/preset

如何使用Jest测试ES6模块


例如:

sum.js

module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
        '@babel/preset-typescript'
    ],
};
const sum=函数(a,b){
返回a+b;
}
导出默认值;
sum.test.js

module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
        '@babel/preset-typescript'
    ],
};
从“/sum”导入总和;
测试('1+2等于3',()=>{
期望(和(1,2))。为(3);
});

唯一的要求是将
测试环境配置到Babel,并添加es2015转换插件:

npm install --save-dev @babel/plugin-transform-modules-commonjs

第1步:

将您的
测试
环境添加到项目根目录中的
.babelrc

{
  "env": {
    "test": {
      "plugins": ["@babel/plugin-transform-modules-commonjs"]
    }
  }
}
第二步:

安装es2015转换插件:

npm install --save-dev @babel/plugin-transform-modules-commonjs


就是这样。Jest将自动启用从ES模块到CommonJS的编译,而无需通知
包内的
Jest
属性的其他选项。json

上述解决方案对我不起作用。我能够解决这个问题:

yarn add --dev babel-jest @babel/core @babel/preset-env @babel/preset-typescript
babel.config.js

module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
        '@babel/preset-typescript'
    ],
};
我正在使用类型脚本的位置


.

这个答案可能已经过时,GarouDan的答案是GarouDan的答案不是ES6模块的官方建议解决方案,而是针对Typescript场景。虽然GarouDan的解决方案包括typescript支持,但下面我提供的链接显示了没有typescript的文件化Jest ES6实现,GarouDan的解决方案就是从中派生出来的。支持typescript所需的更改可以忽略不计,但我同意这与问题无关。