【问题标题】:How to test a async function in Nest js with jest如何用 jest 在 Nest js 中测试异步函数
【发布时间】:2020-10-27 04:30:27
【问题描述】:

我用我的新框架 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)
      });  
    });
  }

【问题讨论】:

    标签: jestjs nestjs


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2018-06-30
      • 1970-01-01
      • 2023-04-06
      • 2020-06-04
      相关资源
      最近更新 更多