jest相关依赖技术选型|青训营笔记

245 阅读5分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 4 天

我们选择做组件库的技术选型包括vue3+vite+ts+jest+eslint+prettier,以下是关于jest与项目有关的技术选型笔记。

使用vite

Jest可用于使用 vite 通过本机ESM提供源代码的项目,以提供一些前端工具。

due to how the plugin system from vite works

Jest不完全受vite支持,但仍有一些使用 vite-jest进行一流Jest集成的工作示例,

  • vite jest的限制 limitation of the vite-jest

    1. 每次必须手动引用 It's not automatically injected into each module. To access it, you must import it from @jest/globals: import { jest } from '@jest/globals'

    2. 不支持windows

    3. 覆盖报告可能崩溃 Coverage Report May be broken

    4. Jest目前在ESM中不支持Jest.mock。

      1. 实验性的API(jest.unstable_mockModule),但必须将其与顶级等待 top-level await 和动态导入结合使用
    5. ECMAScript Modules · Jest

请参阅 vite guide开始。

或者,您可以使用 vitest

Vitest 要求 Vite >=v3.0.0 和 Node >=v14

支持 Typescript

方法一:通过 babel 来支持 Typescript

由于 Babel 对 Typescript 的支持是通过代码转换(Transpilation)实现的,而

Jest 在运行时并不会对你的测试用例做类型检查。故需要在测试之前先进行类型检查或使用tsc将ts改为js

版本

"@babel/core": "^7.20.12",

"@babel/preset-env": "^7.20.2",

"@babel/preset-typescript": "^7.18.6",

步骤

  1. 使用 Babel 指引

    1. What is Babel? · Babel

      1. 功能

        1. 转换语法
        2. 目标环境中缺少的 Polyfill 功能(通过第三方 polyfill,例如core-js
        3. 源代码转换 (codemods)
        4. 和更多!(查看这些视频以获取灵感
      2. // Babel Input: ES2015 arrow function
        [1, 2, 3].map(n => n + 1);
        
        // Babel Output: ES5 equivalent
        [1, 2, 3].map(function(n) {
          return n + 1;
        });
        
    2. yarn add --dev babel-jest @babel/core @babel/preset-env

    3. 将 Babel 配置为 Jest 可感知的

      1. 如果 process.env.NODE_ENV 没有被设置成其它值,Jest 会把它设置成 'test' 。你可以运用在配置项中,从而根据实际情况设定适用于 Jest 的编译。
      2. //babel.config.js
        /module.exports = api => {
          const isTest = api.env('test');
          // 你可以使用 isTest 来决定需要使用到的预设和插件。
        
          return {
            // ...
          };
        };
        
      3. 安装jest时会自动安装babel jest,如果项目中存在babel配置,则会自动转换文件。为了避免这种行为,可以显式重置变换配置选项:
      4. //jest.config.js
        module.exports = {
          transform: {},
        };
        
  2. @babel/preset-typescript

  3. @babel/preset-typescript 添加到 babel.config.js 中的 presets 列表中。

//babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', {targets: {node: 'current'}}],
    '@babel/preset-typescript',
  ],
};
  1. 对测试用例进行类型检查: ts-jesttsc

    1. ts-jest

    2. TypeScript预处理器,

      支持jest的源代码映射,可以使用jest测试用TypeScript编写的项目。

    3. TypeScript 编译器 tsc

      • 单独直接运行/
      • 作为构建流程的一部分
  2. jest进行测试

注意事项

  1. 由于Babel不进行类型检查,语法正确但无法通过TypeScript类型检查的代码可能会成功转换,并且通常以意外或无效的方式进行转换。

  2. 此插件不支持export =import =,因为它们无法编译到ES.next。这些是import/export的TypeScript专用形式。

    1. 临时应对办法:

      1. Use the plugin babel-plugin-replace-ts-export-assignment to transform export =.
      2. 转换为使用export defaultexport const,并import x, {y} from "z"
  3. tsconfig.json的更改没有反映在babel中。构建过程将始终表现得像打开了isolatedModules一样,然而,有Babel原生替代方法来设置许多tsconfig.json选项

  4. 问:为什么Babel不允许导出varlet

    1. 答:TypeScript编译器根据值是否发生突变而动态更改这些变量的使用方式。归根结底,这取决于类型模型,并且不在Babel的范围之内。尽最大努力实现将变量的上下文相关用法转换为始终使用Namespace.Value版本而不是Value,以防它在当前文件之外发生突变。因此,允许var或从Babellet(因为变换尚未编写)在使用时更有可能显示为错误,如果它不是const

方法二:ts预处理器 ts-jest

TypeScript预处理器,

支持jest的源代码映射,可以使用jest测试用TypeScript编写的项目。

Type definitions 类型定义

方法一:使用Jest附带的类型定义,并在每次更新Jest时进行更新。

import {describe, expect, test} from '@jest/globals';

See the additional usage documentation of describe.each/test.each and mock functions.

此方法必须使用在vite搭建的项目里: 根据vite jest的限制 limitation of the vite-jest

It's not automatically injected into each module. To access it, you must import it from @jest/globals: import { jest } from '@jest/globals'

方法二:@types/jest 提供jestglobal的类型

The @types/jest package provides types for Jest globals without a need to import them.

www.jestjs.cn/docs/gettin…

yarn add --dev @types/jest

版本

注意:

@types/jest is a third party library maintained at DefinitelyTyped, hence the latest Jest features or versions may not be covered yet.

Try to match versions of Jest and @types/jest as closely as possible. For example, if you are using Jest 27.4.0 then installing 27.4.x of @types/jest is ideal.

因为jest 版本号为26.0.0,故@types/jest 版本号也为26.0.0

调试配置的坑

test : jest

  1. 您似乎正在使用本机 ECMAScript 模块配置文件,该文件仅在异步运行 Babel 时受支持。

解决: 更改babel.config.js为babel.config.cjs

  1. 然后出现sytanx错误 jest scss SyntaxError: Invalid or unexpected token

解决: 将该段代码注释、删除后仍存在相同错误,后经检索发现是jest.config.cjs中未添加scss及png文件等的mock配置

参考:jest unexpected token when importing css

该错误是由于 Jest 试图将 CSS 解析为 JavaScript,这不会起作用。因此,根据关于处理静态资产的 Jest 文档,处理此问题的更新方法是 3 个步骤

1 在你package.json添加这个

{
  "jest": {
    "moduleNameMapper": {
      "\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
    }
  }
}

2 然后创建以下两个文件:

// __mocks__/styleMock.jsmodule.exports = {};

3

// __mocks__/fileMock.jsmodule.exports = 'test-file-stub';