vitest踩坑记:奇奇怪怪问题汇总

1、Optional chaining cannot appear in left-hand side

window.config?.http = http; // 报错代码

原因:rollup的问题

The error is thrown by acorn, which is Rollup's embedded parser. However, without a reproduction or information about the file that is throwing the error, I have little hope anyone will be able to help you. I think it is also possible that it tries to import a non-JavaScript file which contains some .? in some place.

In any case, even though Rollup emits the error, Rollup also emits all the necessary information about the error location in form of the Error.loc and Error.frame attributes. If angular CLI is swallowing this information, it should be a ticket to them to expose it, otherwise it is indeed close to impossible to debug this.

解决:替换?.

window.config && (window.config.http = http)

2、Cannot find module ‘@/assets/controls/con_toggle.png’**

icon: require('@/assets/controls/con_toggle.png')

原因:require是webpack中的模块引入方式,vite不支持,而我所兼容的是webpack打包的项目,且由于多种原因无法更换为vite
解决:要么替换require的写法,要么使用vite插件,我选择的后者(比网上推崇的vite-plugin-require-transform好用多了)

import vitePluginRequire from 'vite-plugin-require';

plugins: [
    vitePluginRequire({
        fileRegex: /.js$|.vue$/
    })
],

3、Error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.

这种异常的概率就很普遍了,且有很多种异常情况,具体就需要自己慢慢注释代码推断了。本项目中,经过推断,是因为js文件中使用jsx的语法,导致无法解析。
两个方案:改后缀为JSX、使用插件处理。
选择了后者:

import vueJsx from '@vitejs/plugin-vue-jsx'


plugins: [
        vueJsx({
            include: [/\.js$/]
        }),
],

4、window is not defined

毫无疑问代码中使用了window,前端也肯定会出现window…
原因:默认是node环境,node环境下是没有window对象的
解决:单文件环境变量,反正0.28.5版本的vitest配置environment是没有任何卵用的

environment: 'jsdom', // 无效

/**
 * @vitest-environment jsdom // (目标文件顶部,有效)
*/

5、 undefined is not a constructor or null / undefined is not a function 等等

明明在模块中定义了相关方法/类等,却无法导入,抛异常,但是dev环境代码很正常。如下:

 FAIL  src/boards/base/save.spec.js [ src/boards/base/save.spec.js ]
TypeError: Class extends value undefined is not a constructor or null
 ❯ src/boards/base/submit.js:8:31
      6| import { sphericalDistance } from '@b/tags';
      7|
      8| export class tagSubmit extends tagSave {
       |                               ^
      9|
     10|
 ❯ src/boards/index.js:4:31
 ❯ src/boards/submit.js:7:31

原因:模块之间存在相互引用,vitest无法正确解析,导致undefined报错
解决:通过源代码解耦

你可能感兴趣的:(单元测试,javascript,前端,vue.js,vitest)