use*_*695 5 javascript testing mongodb jestjs
我在这个玩笑测试中遇到了两个问题:
Content集合一次,而不是在测试内部执行此操作?我确实收到此错误:
测试运行完成后,Jest 一秒钟都没有退出。这通常意味着测试中存在未停止的异步操作。考虑运行 Jest--detectOpenHandles以解决此问题。
我不明白为什么我的异步代码没有停止......
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()
})
})
})
Run Code Online (Sandbox Code Playgroud)
解析器
import { articleGetContent } from '../models/article'
export default {
Query: {
articleGetContent: async (obj, { id }, { token }) => articleGetContent(id, token)
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我的数据库类的样子
数据库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({})
}
}
Run Code Online (Sandbox Code Playgroud)
关于第二个问题,我希望你在 github 上发现了一些关于它的问题。一般来说,问题会在调试日志中描述。Jest 与 Promise 一起使用,因此,除了已解决之外,您不应该将任何异步操作置于任何状态。
在您的情况下,您打开了数据库连接,因此您需要disconnect为数据库类实现另一种方法,此文档链接将为您提供帮助,但我想您已经拥有它,因为它不是完整的 db.js 文件(我看到一些自定义方法dropDB。这里的主要思想是将其放在afterAll钩子中:
afterAll(() => db.disconnect());
页面底部的很好的例子
第一个问题怎么样,这实际上取决于您在方法中所做的事情dropDB。如果您正在运行删除 collection的方法,您可以将对此集合的引用存储在外部某处并使用它,因为它将自动创建新的集合,但很高兴看到此方法。
此外,您的异步测试是以错误的方式创建的,您可以在此处阅读更多信息,例如在我的更新中。您需要在测试开始时运行此函数:expect.assertions(number)
Expect.assertions(number) 验证测试期间是否调用了一定数量的断言。这在测试异步代码时通常很有用,以确保回调中的断言确实被调用。
| 归档时间: |
|
| 查看次数: |
3447 次 |
| 最近记录: |