NestJS - 测试套件无法运行无法从“comment/comment.entity.ts”中找到模块“src/article/article.entity”

Erg*_*ros 8 testing unit-testing typescript jestjs nestjs

我需要 nestjs 和 jest 测试方面的帮助。我是 NestJS 的新手,在运行测试时遇到了无法找到模块错误的问题。

我正在尝试测试我的服务,当我运行测试时,我收到了错误消息:

src/article/article.service.spec.ts ? 测试套件无法运行

Cannot find module 'src/article/article.entity' from 'comment/comment.entity.ts'

Require stack:
  comment/comment.entity.ts
  article/article.entity.ts
  article/article.service.spec.ts

   6 |   ManyToOne,
   7 | } from 'typeorm';
>  8 | import { Article } from 'src/article/article.entity';
     | ^
   9 | 
  10 | @Entity()
  11 | export class Comment {

  at Resolver.resolveModule (../node_modules/jest-resolve/build/index.js:307:11)
  at Object.<anonymous> (comment/comment.entity.ts:8:1)
Run Code Online (Sandbox Code Playgroud)

这种类似的错误通过不同控制器、服务等的所有其他测试出现。

这是我要测试的代码。

article.service.ts

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Article } from "./article.entity";
import { ArticleRepository } from "./article.repository";
import { ArticleDTO } from "./dto/article.dto";
import { DeleteResult } from "typeorm";
import { ArticleRO } from "./dto/article.response";
import { UserRepository } from "src/user/user.repository";

@Injectable()
export class ArticleService {
  constructor(
    private readonly articleRepository: ArticleRepository,
    private readonly userRepository: UserRepository
  ) {}

  async getAllPosts(): Promise<ArticleRO[]> {
    return await this.articleRepository.find();
  }
}
Run Code Online (Sandbox Code Playgroud)

article.repository.ts

import { Repository, EntityRepository } from 'typeorm';
import { Article } from './article.entity';
@EntityRepository(Article)
export class ArticleRepository extends Repository<Article> {
}
Run Code Online (Sandbox Code Playgroud)

article.service.specs.ts

import { Test, TestingModule } from "@nestjs/testing";
import { getRepositoryToken } from "@nestjs/typeorm";
import { Article } from "./article.entity";
import { ArticleRepository } from "./article.repository";
import { ArticleService } from "./article.service";
import { ArticleRO } from "./dto/article.response";

describe("PostService", () => {
  let service: ArticleService;
  let articleRepository: ArticleRepository;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ArticleService,
        {
          provide: getRepositoryToken(Article),
          useClass: ArticleRepository,
        },
      ],
    }).compile();

    service = module.get<ArticleService>(ArticleService);
    articleRepository = module.get<ArticleRepository>(
      getRepositoryToken(Article)
    );
  });

  it("should be defined", () => {
    expect(service).toBeDefined();
  });
  describe("findAll", () => {
    it("should return an array of cats", async () => {
      const result: ArticleRO[] = [];
      jest.spyOn(service, "getAllPosts").mockResolvedValueOnce(result);

      expect(await service.getAllPosts()).toBe(result);
    });
  });
});


Run Code Online (Sandbox Code Playgroud)

评论.实体.ts

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  ManyToOne,
} from 'typeorm';
import { Article } from 'src/article/article.entity';

@Entity()
export class Comment {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  author: string;

  @Column()
  content: string;

  @CreateDateColumn()
  createdAt: Date;

  @ManyToOne(
    () => Article,
    article => article.comments,
  )
  article: Article;
}
Run Code Online (Sandbox Code Playgroud)

package.json 中有我的笑话设置。

"jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
Run Code Online (Sandbox Code Playgroud)

我试图将我的 rootDir 更改为“./src”,但这不起作用。

我用 nest new blabla 生成了项目。所以我的笑话设置是默认的。也许我在测试中模拟自定义存储库时做错了。

Mat*_*out 23

更改为相对导入

\n

VSCode 设置可以自动执行此操作。

\n

我必须更改 VSCode 导入设置才能使用 TypeScript 的相对路径。默认情况下,VSCode 使用“最短”路径导入,看起来像src/auth/user.entity. 我的 NestJS 应用程序编译良好,但我遇到了与您相同的 Jest 测试错误。

\n

将TypeScript \xe2\x80\xba Preferences: Import Module Specifier设置更改为relative后,模块将像../auth/user.entity. (确保您正在更改 TypeScript 的设置,因为 JavaScript 的设置相同。我都更改了。)。

\n

进行这些模块导入更改修复了我的 NestJS Jest 测试问题,以及类似的Cannot find module \'src/article/article.entity\' from \'comment/comment.entity.ts\'样式错误。

\n

有关更改 VSCode typescript 首选项的更多详细信息如下/sf/answers/3719630001/

\n


小智 12

不要在你的应用程序中使用像“src/article/article.entity”这样的路径,这些在编译后不可用。而是采用像“../../article/article.entity”这样的相对路径(这只是一个猜测的路径)......问候

  • 对我来说,这个解决方案就像魔术一样有效。浪费了时间之后,做了这个简单的技巧就成功了! (2认同)

小智 6

我遇到了同样的问题,但通过添加这些代码行解决了/test/jest-e2e.json

  "moduleNameMapper": {
    "^src/(.*)": "<rootDir>/../src/$1"
  }
Run Code Online (Sandbox Code Playgroud)


Par*_*hal 5

您可以通过配置moduleNameMapper选项告诉 Jest 如何解析模块路径,这在您使用模块别名 等包使用绝对路径时非常有用。将这些行添加到您的 Jest 配置中:

{
  // ...

  "jest": {
    // ...

    "moduleNameMapper": {
      "^src/(.*)$": "<rootDir>/$1"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

现在src/将查看以 开头的模块,默认情况下<rootDir>/这是src文件夹(这在上面配置了几行)。查看上面的文档链接,了解您可以用它做什么。

我不知道使用绝对路径有什么问题,正如另一个回复所说,它不仅有用,而且在 NestJS 和 Angular 中也能正常工作。

  • 该片段不起作用,它必须在映射时再次指定实际的“路径”,如“^src/(.*)$”:“&lt;rootDir&gt;/src/$1”对我有用! (4认同)
  • 我已经在项目根目录中的 package.json 的 jest 部分中包含了这个,但我没有找到它 - 必须将其添加到 test/jest-e2e.json 中,稍微修改为 ```"^src/(。 *)": "&lt;rootDir&gt;/../src/$1"``` (4认同)