我正在测试使用cloudant的Web应用程序。我在beforeAll()中设置了一个测试数据库,并希望在afterAll()中的所有测试之后将其删除。
执行之前的代码,并创建了数据库,但是由于某种原因,之后的代码未执行。更确切地说,不会执行对cloudant api的调用。在前后使用相同的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 }
delete方法定义如下:
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函数。
答案 0 :(得分:1)
尝试这样的事情:
afterAll(async () => {
await Promise.resolve().then(console.log);
});