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

And*_*rde 3 jestjs nestjs

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

\n
\xe2\x97\x8f  Cannot log after tests are done. Did you forget to wait for something async in your test?\n    Attempted to log "SUCCESS conection to MEMCACHED server".\n\n      21 |   // this function Stores a new value in Memcached.\n      22 |   setKey(key : string, value : string , timeExp:number) : Promise<boolean>{\n    > 23 |     // Transform the callback into a promise to be used in the controller\n         |                 ^\n      24 |     return new Promise((resolve,reject) =>{\n      25 |       // Using memcached api to set a key\n      26 |       memcached.set(key, value, timeExp, async function (err) {\n\n      at BufferedConsole.log (../node_modules/@jest/console/build/BufferedConsole.js:201:10)\n      at modules/cache/application/cache.service.ts:23:17\n      at allocate (../node_modules/jackpot/index.js:125:5)\n      at Socket.either (../node_modules/jackpot/index.js:166:5)\n
Run Code Online (Sandbox Code Playgroud)\n

但这是我的测试文件

\n
describe('Cache Controller', () => {\n  let controller: CacheController;\n\n  beforeEach(async () => {\n    const module: TestingModule = await Test.createTestingModule({\n      controllers: [CacheController],\n    }).compile();\n\n    controller = module.get<CacheController>(CacheController);\n  });\n\n  it('should be defined', () => {\n    expect(controller).toBeDefined();\n  });\n});\n\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  • 这是出现错误的函数(如果我不测试这个函数,不知道为什么)
  • \n
\n
// this function Stores a new value in Memcached.\n  async setKey(key : string, value : string , timeExp:number) : Promise<boolean>{\n    // Transform the callback into a promise to be used in the controller\n    return await new Promise((resolve,reject) =>{\n      // Using memcached api to set a key\n      memcached.set(key, value, timeExp, function (err) {\n        if (err) return reject(err);\n        resolve(true)\n      });  \n    });\n  }\n
Run Code Online (Sandbox Code Playgroud)\n

小智 5

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

将测试用例定义为异步函数并调用await 等待返回值。

it('Test case name', async () => {
   // Await something
   // Expect something
})
Run Code Online (Sandbox Code Playgroud)