简介
buble-jest 是一个可以在 Jest 中使用 Buble 进行 ES6+语法转换的 npm 包。Buble 是一个能够帮助开发者将ES6+语法转换为ES5的JS编译器,同时还具有很高的转换速度。通过使用 buble-jest,我们可以让 Jest 在运行测试用例之前自动地将我们的ES6+语法代码转换成ES5语法的代码。
安装
在安装 buble-jest 之前,需要首先安装 Jest 和 Buble:
npm install --save-dev jest npm install --save-dev buble
然后,安装 buble-jest:
npm install --save-dev buble-jest
使用方法
为了让 Jest 使用 buble-jest,我们需要在 Jest 的配置文件中进行如下设置:
// jest.config.js module.exports = { transform: { "^.+\\.js$": "buble-jest", }, };
这样,当 Jest 运行测试用例时,在遇到 .js
后缀的文件时,就会使用 buble-jest 进行转换。
除此之外,我们还可以在 Jest 的命令行选项中,使用 --transform
参数来设置使用哪种转换器进行代码转换:
jest --transform=buble-jest
或者,我们可以在单个测试文件的头部中,使用注释来指定使用 buble-jest 进行转换:
// @ts-nocheck /* eslint-disable */ /* @jsx h */ // buble-jest will transform this file import { h, render } from "preact";
但是需要注意的是,指定注释的方式只在单个文件中生效,而在 Jest 配置文件中使用 transform 字段,则是全局生效的。
示例代码
// src/index.js const add = (a, b) => a + b; export default add;
// __tests__/index.test.js import add from "../src/index.js"; test("add 1 + 2 equals 3", () => { expect(add(1, 2)).toBe(3); });
在不使用 Buble 时,这段代码将会报错,因为 Jest 默认不支持转换 ES6+ 语法。但是,如果我们在 Jest 配置文件中进行如下设置,则代码将能够成功运行:
// jest.config.js module.exports = { transform: { "^.+\\.js$": "buble-jest", }, };
然后,执行 Jest 的测试命令,可以看到测试成功通过:
-- -------------------- ---- ------- --- ---- - ---------------- ---- ------------------- - ---- ---- ----------------------- - --- - - - ------ - ----- ---- ------- - ------- - ----- ------ - ------- - ----- ---------- - ----- ----- ------ --- --- ---- -------
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/60066c8cccdc64669dde54a5