我有一个js文件,它提供了一些db操作。此文件仅适用于可以链接的promises。为了测试这个类,我使用了一个异步函数。
问题是,每当我在测试函数中使用promises时,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 ()
函数应该包含更多的测试,只是为了解决这个问题,我缩短了它。
需要说明的是:如果我只测试不包含另一个promise链的testGetFaculties ()
类型的方法,那么它的工作方式应该是这样的。
你知道为什么会是这样吗?
发布于 2018-12-11 04:19:51
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');
} )
} );
} );
https://stackoverflow.com/questions/53712865
复制相似问题