我有一个 js 文件,它提供一些数据库操作。该文件仅适用于可链接的 Promise。为了测试该类,我使用了异步函数。
问题是,每当我在测试函数中使用 Promise 时,it
函数就会在以后的所有其他测试中被阻止。
这里有两个例子:
'use strict'
const exec = require('child_process').exec
const path = require('path')
const request = require('request')
const expect = require('chai').expect
const createTableStatements = require('../data')
test()
async function test () {
await testGetUser()
console.log('1')
await testGetFaculties()
}
function testGetUser () {
return new Promise((resolve1) => {
describe('test get user', function () {
const db = require('../dbInterface')
it('test get user should be complete', function () {
db.dbFunctions.dropAll()
.then(onResolve => {
return db.dbFunctions.createTable(createTableStatements.createTableStatements.user)
}
)
.then(() => {
console.log('success create user table')
return db.dbFunctions.addUser('1', 'firstName', 'lastName', 'email')
})
.then(resolve => {
return db.dbFunctions.getUser('email', undefined)
})
.then(result => {
expect(result.toString().includes('dummy')).to.equal(false)
})
.then(resolve => {
return db.dbFunctions.dropAll()
})
.then(resolve => {
console.log('resolve')
resolve1()
})
.catch(err => console.log(err))
})
})
})
}
function testGetFaculties () {
return new Promise(resolve => {
describe('test get faculties', function () {
let db
before(function () {
db = require('../dbInterface')
})
console.log('displayed')
it('should work', function () {
console.log('locked')
expect(db.dbFunctions.getFaculties('hsa')).to.be.an('array').that.does.include('Science')
resolve()
})
})
})
}
这是输出
resolve
1
displayed
如您所见,console.log('locked')
没有被处理。
到目前为止我发现,只有当我在 then 函数中调用 expect
时才会遇到这个问题。但这对于我的测试来说是必要的。
test()
函数应该包含更多的测试,只是为了这个问题我缩短了它。
澄清一下:如果我只测试 testGetFaculties ()
的方法类型,它内部不包含另一个 promise 链,那么它应该像它应该的那样工作。
知道为什么会这样吗?
最佳答案
很可能 console.log( 'locked' );
没有执行任何操作,因为您之前的测试用例根本没有完成。
在 Promise 中写入 describe
、it
、before
并包含未返回的 Promise 是不应该做的事情。
更好的测试用例看起来像:
'use strict'
const exec = require('child_process').exec
const path = require('path')
const request = require('request')
const expect = require('chai').expect
const createTableStatements = require('../data')
// You use this in both test cases anyway
const db = require('../dbInterface');
describe('test get user', function () {
it('test get user should be complete', function () {
return db
// ^ returning promise will make sure that the test ends when the promise ends.
.dbFunctions
.dropAll()
.then(onResolve => { ... } )
...
)
} );
} );
describe('test get faculties', function () {
it('should work', function () {
return db
// ^ returning promise will make sure that the test ends when the promise ends.
.dbFunctions
.getFaculties('hsa')
.then( value => {
// ^ You actually need to test the value of the resolve promise
expect( value ).to.be.an('array').that.does.include('Science');
} )
} );
} );
关于javascript - 将其锁定在 chai 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53712865/