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

Jest测试异常:扫描非相关代码问题排查

问题:Jest测试Express/TypeScript应用时扫描执行大量非相关代码

我正在开发一个基于TypeScript的Express示例应用,目前尝试集成Jest进行测试。我的目标是仅测试AuthService服务类,但运行测试时发现Jest会扫描并执行大量无关代码,而非仅针对auth.service.ts。

错误截图

从错误栈追踪可以看出,Jest执行的内容远超预期。以下是相关文件代码:

auth.service.ts

import { generateUuid, isPasswordMatching, redisClient } from '../utils';
import { getUserService } from './user.service';

class AuthService {
  private userService = getUserService();

  async login(username: string, password: string): Promise<string | null> {
    const user = await this.userService.getUserByUsername(username);

    if (!user) return null;

    if (!(await isPasswordMatching(password, user.password))) return null;

    if (!user.token) {
      user.token = generateUuid();
      await user.save();
    }

    await redisClient.set(user.token, user.userId);

    return user.token;
  }
}

const authService = new AuthService();

export const getAuthService = (): AuthService => {
  return authService;
};

测试文件

import { getAuthService } from '../../src/services/auth.service';

const authService = getAuthService();

test('auth service init', () => {
  expect(authService).not.toBeNull();
});

更新:补充auth.route.ts文件

import { Request, Response, Router } from 'express';
import { getAuthService } from '../services';
import { loginSchema, validateParams } from '../validators';

const authService = getAuthService();

export const authRoute = (router: Router) => {
  router.post('/login', async (req: Request, res: Response) => {
    const { data, error } = await validateParams(req.body, loginSchema);

    if (error) {
      res.status(400).send({ message: error });
      return;
    }

    const token = await authService.login(data.username, data.password);

    if (!token) {
      res.status(400).send({ message: `Invalid credentials.` });
      return;
    }

    res.status(200).send({ token });
  });
};

是否有人知道问题的可能原因?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:22:45