首页 > 解决方案 > Nestjs 单元测试中不支持从“描述”返回 Promise

问题描述

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

不支持从“描述”返回 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();
  });
});

标签: javascriptnode.jsunit-testingtestingnestjs

解决方案


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


推荐阅读