Jestjs 如何使用jest测试Nest js中的异步函数

Jestjs 如何使用jest测试Nest js中的异步函数,jestjs,nestjs,Jestjs,Nestjs,我用我的新框架Nest js做了一个简单的测试,但是第一次运行命令npm run test时我发现了这个错误 ● Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "SUCCESS conection to MEMCACHED server". 21 | // this function

我用我的新框架Nest js做了一个简单的测试,但是第一次运行命令npm run test时我发现了这个错误

●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log "SUCCESS conection to MEMCACHED server".

      21 |   // this function Stores a new value in Memcached.
      22 |   setKey(key : string, value : string , timeExp:number) : Promise<boolean>{
    > 23 |     // Transform the callback into a promise to be used in the controller
         |                 ^
      24 |     return new Promise((resolve,reject) =>{
      25 |       // Using memcached api to set a key
      26 |       memcached.set(key, value, timeExp, async function (err) {

      at BufferedConsole.log (../node_modules/@jest/console/build/BufferedConsole.js:201:10)
      at modules/cache/application/cache.service.ts:23:17
      at allocate (../node_modules/jackpot/index.js:125:5)
      at Socket.either (../node_modules/jackpot/index.js:166:5)
●  测试完成后无法登录。您是否忘记在测试中等待异步的内容?
试图记录“成功连接到MEMCACHED服务器”。
21 |//此函数在Memcached中存储一个新值。
22 | setKey(key:string,value:string,timeExp:number):承诺{
>23 |//将回调转换为在控制器中使用的承诺
|                 ^
24 |返回新承诺((解决、拒绝)=>{
25 |//使用memcached api设置密钥
26 | memcached.set(键、值、timeExp、异步函数(err){
在BufferedConsole.log(../node_modules/@jest/console/build/BufferedConsole.js:201:10)
at modules/cache/application/cache.service.ts:23:17
分配时(../node_modules/jackpot/index.js:125:5)
在Socket.other(../node_modules/jackpot/index.js:166:5)
但这是我的测试文件

describe('Cache Controller', () => {
  let controller: CacheController;

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

    controller = module.get<CacheController>(CacheController);
  });

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

description('Cache Controller',()=>{
let控制器:缓存控制器;
beforeach(异步()=>{
常量模块:TestingModule=等待测试。createTestingModule({
控制器:[缓存控制器],
}).compile();
控制器=module.get(CacheController);
});
它('应该定义',()=>{
expect(controller.toBeDefined();
});
});
  • 这是得到错误的函数(如果我不测试这个函数,我不知道为什么)
//此函数在Memcached中存储一个新值。
异步setKey(key:string,value:string,timeExp:number):承诺{
//将回调转换为要在控制器中使用的承诺
返回等待新承诺((解决、拒绝)=>{
//使用memcachedapi设置密钥
set(键、值、timeExp、函数(err){
如果(错误)返回拒绝(错误);
解析(真)
});  
});
}

您的异步函数将返回一个承诺

将测试用例定义为异步函数,并调用wait以等待返回值

it('Test case name', async () => {
   // Await something
   // Expect something
})

异步函数将返回一个承诺

将测试用例定义为异步函数,并调用wait以等待返回值

it('Test case name', async () => {
   // Await something
   // Expect something
})