如何使用笑话在Nest js中测试异步功能

时间:2020-07-07 00:31:12

标签: 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 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)

但这是我的测试文件

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();
  });
});

  • 这是收到错误的函数(不知道为什么我不测试此函数)
// this function Stores a new value in Memcached.
  async setKey(key : string, value : string , timeExp:number) : Promise<boolean>{
    // Transform the callback into a promise to be used in the controller
    return await new Promise((resolve,reject) =>{
      // Using memcached api to set a key
      memcached.set(key, value, timeExp, function (err) {
        if (err) return reject(err);
        resolve(true)
      });  
    });
  }

1 个答案:

答案 0 :(得分:2)

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

将测试用例定义为 async函数,然后调用await等待返回值。

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