【问题标题】:Promise call in afterAll not executedafterAll 中的 Promise 调用未执行
【发布时间】:2019-08-08 08:57:25
【问题描述】:

我正在测试一个使用 cloudant 的 Web 应用程序。我在 beforeAll() 中设置了一个测试数据库,并希望在 afterAll() 中的所有测试之后将其删除。

之前的代码被执行,我创建了数据库,但由于某种原因,之后的代码没有被执行。更准确地说,对 cloudant api 的调用没有执行。在 before 和 after 都使用处理 promise 的相同 API。

在我的 test.js 中

const cloudant = require('../storage/cloudant');

const dbname = 'testdb';
const doc = { _id: 'testDocument' };
const dbConfig = { dbname, doc };

beforeAll(() => {
  cloudant.createDB(dbname)
    .then(res => console.log(res))
    .then(() => cloudant.createDocument(dbConfig));
});

afterAll(() => {
  console.log('It is called');
  cloudant.deleteDatabase(dbname).then((res) => console.log(res)).catch(e => console.log(e));

// test templates functions
test('Read documnet from cloudant', async () => {
  const response = await cloudant.readDocument(dbname, doc._id);
  expect(response._id).toBe(doc._id);
});

我希望在测试执行后删除数据库。然而,在 afterALL 中唯一需要调用的是 console.log; deleteDatabase 调用没有异常或错误。 deleteDatabase 方法有效。我在一个单独的 js 脚本中对其进行了测试。

cloudant.deleteDatabase(dbname)
  .then((res) => console.log(res))
  .catch(e => console.log(e));

返回{ ok: true }

删除方法定义如下:

 async deleteDatabase(dbname) {
    return this.cloudantDB.db.destroy(dbname);
  }

测试结果如下:

> jest server/test

[2019-08-08T10:58:55.132] [INFO] App-cloudant - creating new db: testdb
[2019-08-08T10:58:55.138] [INFO] App-cloudant - Reading testDocument
  console.log server/storage/cloudant.js:43
    testdb

  console.log server/storage/cloudant.js:44
    testDocument

  console.log server/test/test.js:17
    { ok: true }

[2019-08-08T10:58:55.487] [INFO] App-cloudant - Creating document [object Object]
 PASS  server/test/test.js
  ✓ adds 1 + 2 to equal 3 (2ms)
  ✓ Read documnet from cloudant (515ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        2.184s
Ran all test suites matching /server\/test/i.
  console.log server/test/test.js:22
    It is called

所以 beforeAll 工作,测试成功执行,并且调用了 afterAll 中的 console.log,但没有调用 deleteDatabase 函数。

【问题讨论】:

  • 您可能需要兑现承诺?

标签: node.js jestjs


【解决方案1】:

试试这样的:

afterAll(async () => {
  await Promise.resolve().then(console.log);
});

【讨论】:

  • 谢谢!!当它以这种方式使用异步调用时,它可以工作。但是为什么这在没有异步的 beforeAll 中起作用,但在 afterAll 中却不起作用?
  • 真的没有,必须一直等待异步任务
  • 我刚刚测试了@sp00m 建议并返回了承诺,它也可以正常工作,` afterAll(() => cloudant.deleteDatabase(dbname).then(console.log('deleted') ));`
  • 返回一个promise和使用async是一样的,实际上async把你的函数包装在一个promise中
猜你喜欢
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多