jestjs - 为什么nestjs单元测试在beforeEach而不是beforeAll中创建测试模块?

标签 jestjs nestjs

在nestjs中,测试文件(来自cli的模板)在beforeEach内有Test.createTestingModule,因此它会在每次测试之前重新创建模块。

例如foo.service.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { FooService } from './foo.service';

describe('FooService', () => {
  let service: FooService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [FooService],
    }).compile();

    service = module.get<FooService>(FooService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

但是为什么它在 beforeEach 中而不是在 beforeAll 中?

有什么理由让它出现在 beforeEach 中吗?也许会引起问题?

我看到在 e2e 测试中,应用程序是在 beforeAll 中创建的,所以我不确定为什么单元测试是在 beforeEach 中创建的。

最佳答案

我认为这是因为当您想要执行单元测试时,您通常需要创建模拟和 spy ,这在您想要真正的数据库连接等的 E2E 测试中是不正确的。

如果您在 BeforeAll 中定义模块,那么您需要创建 AfterEach 来清除每个 spy 和模拟的历史记录。

而且由于E2E中的一切都是真实的,如果每次测试都重新初始化所有模块和连接,确实需要很长时间。

关于jestjs - 为什么nestjs单元测试在beforeEach而不是beforeAll中创建测试模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67778895/

相关文章:

nestjs - 如何使动态模块成为全局模块?

node.js - 表迁移文件

node.js - Mongoose/MongoDb 在数组中查找具有反向引用的文档

node.js - NestJS e2e 测试模拟 Session 装饰器

javascript - 如何在 Jest 测试中调用 native console.log 方法?

javascript - 如何测试使用 jest 操作 DOM 的普通 js 代码

javascript - 指定在任何 Jest 设置发生之前运行的代码

reactjs - 使用 testing-library 和 jest 的 React 组件抛出的测试错误

javascript - 如何使用导入构造函数的外部库的 Jest 来测试模块

typescript - 使用 NestJS 基于模式获取多个 Redis 缓存键