Vitest 配置 - 路径导入错误 - 文件是否存在?

问题描述 投票:0回答:1

我在使用 Aurelia 和 Vitest 的存储库中遇到了问题。 结构是这样的:

project-root
│
├── src
│   ├── services
│   │   └── api.js
│   │   └── auth.js
│   ├── views
│   │   └── messages
│   │       ├── messages.js
│   │       └── messages.test.js
│
├── vite.config.ts
├── vitest.config.ts
├── vitest.setup.ts
├── package.json
└── node_modules

messages.js:

import { activationStrategy } from 'aurelia-router';
import { I18N } from 'aurelia-i18n';
import { Api, Auth } from 'services/api';
import { User } from 'services/user';
import { KaDialog } from 'ka-components';

export class VMMessages {
  endpoint = 'messages';

  static inject = [I18N, Api, Auth, User, KaDialog];
  constructor(i18n, api, auth, user, dialog) {
    this.i18n = i18n;
    this.api = api;
    this.auth = auth;
    this.user = user;
    this.dialog = dialog;
  }
}

messages.test.js

import { beforeAll, describe, it, expect, vi } from 'vitest';
import { VMMessages } from './messages';

const messages = new VMMessages({}, {}, {}, {}, {});

it('should return a string', () => {
  expect(true).toBe(true);
});

vite.config.js:

import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      'services': path.resolve(__dirname, 'src/services')
    },
  },
  server: {
    port: 3903
  },
  test: {
    globals: true,
    environment: 'jsdom',
  },
});

vitest.config.js:

import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    setupFiles: 'vitest.setup.js',
    environment: 'jsdom',
    reporters: ['verbose'],
  }
});

vitest.setup.js:

import { resolve } from 'path';
import * as dotenv from 'dotenv';
global.ENVIRONMENT = dotenv.config({
  debug: true,
  processEnv: global.ENVIRONMENT,
  path: resolve(__dirname, `./src/environments/test.env`)
});

现在,当我尝试运行测试时,我收到此错误: 无法解析从“src/views/messages/messages.js”导入“services/api”。文件存在吗?

一切似乎都是正确的,所以我不知道为什么它不起作用,有建议吗?我缺少什么?显然,我期望发生的是 vitest 正确导入我想要测试的视图模型(及其依赖项)并且没有失败的错误。

unit-testing path vite aurelia vitest
1个回答
0
投票

经过几个小时的故障排除后问题得到解决。主要 3 个修复:

  1. 删除 vite.config.js,项目不需要它 - webpack 存在。

  1. vitest.config.js需要这个:

    alias: {
      services: path.resolve(__dirname, './src/services')
    }

而不是这个:

    alias: {
      '@': path.resolve(__dirname, 'src'),
      'services': path.resolve(__dirname, 'src/services')
    }
  1. 在 messages.test.js 中,我必须模拟所有依赖项:

    vi.mock('services/api', () => {
      return {
        Api: class {},
        Auth: class {}
      }
    });
    vi.mock('services/user', () => {
      return {
        User: class {}
      }
    });
    vi.mock("aurelia-i18n", () => {
      return {
        I18N: {}
      }
    });
    vi.mock("ka-components", () => {
      return {
        KaDialog: {}
      }
    });
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.