You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue项目配置Azure MSAL后运行测试出现TS1378错误求助

解决Vue+MSAL测试中的TS1378顶层await错误

1. 确认测试环境的TypeScript配置

主应用的tsconfig.json配置不一定会被测试框架完全继承,多数测试框架会读取专属的测试TS配置文件(比如tsconfig.test.json或tsconfig.vitest.json)。

  • 检查项目中是否存在测试专属TS配置文件,确保其中的配置满足要求:
    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "target": "es2017",
        "module": "esnext",
        "moduleResolution": "bundler",
        "allowTopLevelAwait": true
      }
    }
    
  • 如果测试框架未自动识别该文件,需在测试配置中手动指定:
    以Vitest为例,修改vitest.config.ts:
    import { defineConfig } from 'vitest/config'
    import vue from '@vitejs/plugin-vue'
    
    export default defineConfig({
      plugins: [vue()],
      test: {
        globals: true,
        environment: 'jsdom',
        typescript: {
          tsconfigPath: './tsconfig.test.json'
        }
      }
    })
    

2. 重构MSAL初始化代码,规避顶层await

如果不想依赖测试环境的配置,可以重构MSAL初始化逻辑,把顶层await封装为可调用的异步函数:

原代码(含顶层await):

// msalConfig.ts
import { PublicClientApplication } from '@azure/msal-browser'

const msalInstance = await PublicClientApplication.initialize({
  auth: {
    clientId: 'your-client-id'
  }
})

export default msalInstance

重构后:

// msalConfig.ts
import { PublicClientApplication } from '@azure/msal-browser'

export async function createMsalInstance() {
  return PublicClientApplication.initialize({
    auth: {
      clientId: 'your-client-id'
    }
  })
}

// 应用中使用时
const msalInstance = await createMsalInstance()

测试中可直接调用函数并await,或mock该函数:

// 测试文件
import { createMsalInstance } from '@/config/msalConfig'

vi.mock('@/config/msalConfig', () => ({
  createMsalInstance: vi.fn().mockResolvedValue({
    loginPopup: vi.fn(),
    acquireTokenPopup: vi.fn()
  })
}))

test('测试示例', async () => {
  const instance = await createMsalInstance()
  // 编写测试逻辑
})

3. 配置测试框架支持顶层await

不同测试框架的配置方式略有差异:

Vitest

确保vitest.config.ts中开启正确的模块支持:

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom'
  },
  resolve: {
    conditions: ['node', 'browser']
  }
})

Jest

若使用Jest,需通过Babel配置开启顶层await支持:

  1. 安装依赖:npm install --save-dev @babel/preset-env babel-jest
  2. 创建.babelrc:
{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "node": "current"
      },
      "modules": false,
      "topLevelAwait": true
    }]
  ]
}
  1. 修改jest.config.js:
module.exports = {
  transform: {
    '^.+\\.tsx?$': 'babel-jest'
  }
}

4. 排查其他配置冲突

  • 确认tsconfig.json的compilerOptions中没有设置noImplicitAny等可能冲突的选项
  • 检查IDE使用的TypeScript版本是否与项目依赖版本一致,全局TS版本可能导致配置不生效

内容的提问来源于stack exchange,提问作者Oihane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 16:01:30