我在这个玩笑测试中有两个问题:
Content集合,而不是在测试中这样做?--detectOpenHandles运行Jest来解决此问题。我不明白为什么我的异步代码没有停止..。
import resolvers from 'resolvers/'
import Db from 'lib/db'
const db = new Db()
describe('Resolver', () => {
let token
beforeAll(async () => {
await db.connect()
})
beforeEach(async () => {
token = 'string'
await db.dropDB()
})
afterAll(async () => {
await db.connection.close()
})
describe('articleGetContent()', () => {
test('should return dataset', async () => {
// SETUP
const Content = db.connection.collection('content')
const docs = [{
// some content...
}]
await Content.insertMany(docs)
// EXECUTE
const result = await resolvers.Query.articleGetContent({}, {
id: '123,
language: 'en'
}, {
token
})
// VERIFY
expect.assertions(1)
expect(result).toBeDefined()
})
})
})解析器
import { articleGetContent } from '../models/article'
export default {
Query: {
articleGetContent: async (obj, { id }, { token }) => articleGetContent(id, token)
}
}这就是我的db类的样子
db.js
export default class Db {
constructor (uri, callback) {
const mongo = process.env.MONGO || 'mongodb://localhost:27017'
this.mongodb = process.env.MONGO_DB || 'testing'
this.gfs = null
this.connection = MongoClient.connect(mongo, { useNewUrlParser: true })
this.connected = false
return this
}
async connect (msg) {
if (!this.connected) {
try {
this.connection = await this.connection
this.connection = this.connection.db(this.mongodb)
this.gfs = new mongo.GridFSBucket(this.connection)
this.connected = true
} catch (err) {
console.error('mongo connection error', err)
}
}
return this
}
async disconnect () {
if (this.connected) {
try {
this.connection = await this.connection.close()
this.connected = false
} catch (err) {
console.error('mongo disconnection error', err)
}
}
}
async dropDB () {
const Content = this.connection.collection('content')
await Content.deleteMany({})
}
}发布于 2019-01-06 22:00:48
关于第二个问题,我希望您已经在github上找到了一些关于它的问题。通常,调试日志中将描述此问题。Jest与承诺一起工作,因此,除已解决之外,不应将任何异步操作保留在任何状态下。
在您的示例中,您打开了DB连接,因此您需要为您的DB类实现另一个方法disconnect,指向文档的链接将帮助您,但我想您已经拥有了它,因为它不是完整的db.js文件(我看到了一些自定义方法dropDB )。这里的主要思想是将其放在afterAll钩子中:
afterAll(() => db.disconnect());
页面底部的很好的示例
关于first问题,它实际上取决于您在方法dropDB中所做的事情。如果您正在为滴落收集运行方法,您可以将对这个集合的引用存储在外部的某个地方,并使用它,因为它将自动创建新的方法,但是看到这个方法将是很好的。
Additionally,您的异步测试是以错误的方式创建的,您可以在“我的更新”中读取更多的这里。您需要在测试开始时运行这个函数:expect.assertions(number)
expect.assertions( number )验证在测试期间是否调用了一定数量的断言。在测试异步代码时,这通常很有用,以确保回调中的断言确实被调用。
https://stackoverflow.com/questions/53944843
复制相似问题