Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

集成 E2E 和 UT 踩坑指南 #61

Open
QC-L opened this issue May 26, 2022 · 0 comments
Open

集成 E2E 和 UT 踩坑指南 #61

QC-L opened this issue May 26, 2022 · 0 comments

Comments

@QC-L
Copy link
Owner

QC-L commented May 26, 2022

关于 路径 别名

通常,我们在开发中,会对常引用的路径,为其起一个别名,方便快速引用,去除无用的 ./

通常,我们会在编译层进行配置,如 tsconfig 或者 webpack.config 中进行配置。

但当执行 jest 时,jest 无法识别,我们所设置的别名,因此需要在 jest.config 中将对应的配置进行同步,便于 jest 进行识别:

function makeModuleNameMapper(srcPath: string, tsconfigPath: string) {
  // Get paths from tsconfig
  const { paths } = require(tsconfigPath).compilerOptions

  const aliases: { [key: string]: string } = {}

  // Iterate over paths and convert them into moduleNameMapper format
  Object.keys(paths).forEach((item) => {
      const key = item.replace('/*', '/(.*)')
      const path = paths[item][0].replace('/*', '/$1')
      aliases[key] = srcPath + '/' + path
  })
  console.log(aliases)
  return aliases
}

然后在对应的配置中添加:

{
  // ... other config
  moduleNameMapper: makeModuleNameMapper("<rootDir>", "./tsconfig.json"),
}

升级 React 18 后,@testing-library/react-hooks 已弃用

由于 @testing-library/react 已将 renderHook 集成,因此 @testing-library/react-hooks 将不再更新,但 React 18 以前的项目,依旧有效。

import { renderHook } from '@testing-library/react'

同时集成 cypress 和 jest 时,需要对 tsconfig.json 进行调整

因为 cypress 和 jest 都具有相同的 expect API,因此,类型推导时,会出现推导异常的问题

解决方案:为 cypress/ 文件夹单独配置 tsconfig.json,同时,在根目录忽略 cypress 的类型以及包

./tsconfig.json 的配置如下:

{
  // ...other config
  "compilerOptions": {
    // ...other config
    "types": ["jest"]
  },
  "exclude": [
    "node_modules",
    "cypress"
  ]
}

./cypress/tsconfig.json 内容如下:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "noEmit": true,
    // be explicit about types included
    // to avoid clashing with Jest types
    "types": ["cypress"]
  },
  "include": [
    "../node_modules/cypress",
    "../tsconfig.json",
    "../package.json",
    "./**/*.ts"
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant