我在Nuxt 3中使用了一些utils。vue反应性系统(ref
、computed
…)也直接进口。然而,测试的情况并非如此。
运行导入./useBusinessValidation
可组合文件的规范文件会引发错误ReferenceError: ref is not defined
源文件./useBusinessValidation
:
import { MaybeRef } from "@vueuse/core"
export const useBusinessValidation = <T>(rule: (payload: T) => true | string, payload: MaybeRef<T>) => {
const validation = computed(() => rule(unref(payload)))
const isValid = computed(() => validation.value === true)
const errorMessage = computed(() => isValid.value ? undefined : validation.value as string)
return {
isValid,
errorMessage
}
}
规范文件useBusinessValidation.spec.ts
:
import { useBusinessValidation } from "./useBusinessValidation"
describe('useBusinessValidation', async () => {
it('should be valid with payload respecting the rule', () => {
const rule = (x: number) => x > 0 ? true : `invalid ${x} number. Expected ${x} to be greater than 0.`
const { isValid, errorMessage } = useBusinessValidation(rule, 0)
expect(isValid.value).toBe(true)
expect(errorMessage.value).toBe(undefined)
});
})
和vitest.config.ts
{
resolve: {
alias: {
'~': '.',
'~~': './',
'@@': '.',
'@@/': './',
'assets': './assets',
'public': './public',
'public/': './public/'
}
},
test: {
globals: true,
setupFiles: './test/setupUnit.ts',
environment: 'jsdom',
deps: { inline: [/@nuxt/test-utils-edge/] },
exclude: [
'test/**/**.spec.ts',
'**/node_modules/**',
'**/dist/**',
'**/cypress/**',
'**/.{idea,git,cache,output,temp}/**'
]
}
}
我也试过用@vitejs/plugin-vue
作为
plugins: [Vue()]
在vitest配置中。结果没有成功。
要在vitest中自动导入,请安装unplugin自动导入。
然后,在vitest.config.ts中添加:
import AutoImport from 'unplugin-auto-import/vite';
export default defineConfig({
...
plugins: [
AutoImport({
imports: [
'vue',
// could add 'vue-router' or 'vitest', whatever else you need.
],
}),
]
});