将 async/await 改为 Promise

问题描述

我想更改以下异步/等待代码

const mongoose = require('mongoose')
const supertest = require('supertest')
const app = require('../app')

const api = supertest(app)

test("total number of blogs",async () => {
  const response = await api.get('/api/blogs')
  
  expect(response.body).toHaveLength(1)
})
      

afterall(() => {
  mongoose.connection.close()
})

这样的承诺:

const mongoose = require('mongoose')
const supertest = require('supertest')
const app = require('../app')

const api = supertest(app)

test("total number of blogs",() => {
  api.get('/api/blogs')
    .then( response => {
      expect(response.body).toHaveLength(1)
    })
})


afterall(() => {
  mongoose.connection.close()
})

我无法正确解决它,并且不断收到错误消息:

enter image description here

解决方法

为了澄清@jonrsharpe 的评论,您应该从测试函数中返回承诺:

test("total number of blogs",() => {
  return api.get('/api/blogs')
    .then( response => {
      expect(response.body).toHaveLength(1)
    })
})
,

在第一个版本中,您在测试中返回一个 Promise。测试库收到此承诺并等待它完成,然后才会将测试视为“已完成”。

所以你要做的是:

test("total number of blogs",() => {
    return api.get('/api/blogs')
      .then( response => {
        expect(response.body).toHaveLength(1)
      })
  
})

不要忘记第一个例子已经可以使用 promises(async/await 只是 promises)

编辑是因为我查看了文档:p

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...