【问题标题】:Returning a Promise from "describe" is not supported In Nestjs Unit testingNestjs 单元测试中不支持从“描述”返回 Promise
【发布时间】:2021-06-19 00:42:06
【问题描述】:

我想使用 mongoose 对 Nestjs 中的服务进行单元测试。 最后出现这个错误

不支持从“describe”返回 Promise。测试必须同步定义。

从“describe”返回一个值将导致 Jest 未来版本的测试失败。

import { Test, TestingModule } from '@nestjs/testing';
import { MongooseModule } from '@nestjs/mongoose';

import { closeInMongodConnection, rootMongooseTestModule } from '../test-utils/mongo/MongooseTestModule';
import { UserSchema } from './user.model';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

describe('UserController', async () => {
  let controller: UsersController;
  let service: UsersService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [rootMongooseTestModule(), MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],
      controllers: [UsersController],
      providers: [UsersService],
    }).compile();

    controller = module.get<UsersController>(UsersController);
    service = module.get<UsersService>(UsersService);
  });

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

  it('should return all the events', async () => {
    const result = {
      totalDocs: 0,
      resource: [],
    };

    const data = await service.findAll();
    expect(data).toEqual(result);
  });
  

  afterAll(async () => {
    await closeInMongodConnection();
  });
});

【问题讨论】:

  • 请问您可以修复问题中的编辑吗?代码块中似乎嵌套了一个 sn-p?

标签: javascript node.js unit-testing testing nestjs


【解决方案1】:

Jest(不是 Nest)不支持从 describe 回调返回承诺。您可以进行异步测试,但测试套件(describe 块)需要同步。从顶级 describe 块中删除 async

【讨论】:

  • 在我的代码中,创建初始状态(在每个测试中使用)需要异步请求。我是否只需要在每次测试中重新建立该状态?有没有办法在测试之外进行异步设置?
  • 为什么不使用beforeEachbeforeAll 可以是async 并在测试之前运行
猜你喜欢
  • 2019-10-31
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 2016-05-06
  • 2016-01-25
  • 2014-03-28
  • 1970-01-01
相关资源
最近更新 更多