问题描述
我试图理解为什么玩笑测试会引发错误,这是我的代码: monogodb 连接:
const { MongoClient } = require('mongodb')
MongoClient.connect(
process.env.MONGODB_URL,{
useNewUrlParser: true,useUnifiedTopology: true,},async (error,client) => {
if (error) {
console.log('Unable to connect')
throw error
}
console.log('MongoDB is connected!')
//Global variable defined and will be reached by all scripts (routers) of App.js in server
global.db = client.db(process.env.DATABASE_NAME)
}
)
导致问题的测试脚本示例(还有另一个):
/* eslint-disable no-undef */
const request = require('supertest')
const app = require('../server/app-source')
test('Signup as a current user,so it will return 409 status code',async () => {
await request(app)
.post('/sign-up')
.send({
username: 'test user',password: 'test password',confirmPass: 'test password',email: 'test@test.com',role: 'Customer',})
.expect(409)
})
test('Access the homepage as a user (test user which created above)',async () => {
await request(app)
.post('/login')
.send({
username: 'test user',})
.expect(200)
})
test('Access the homepage as non-user',async () => {
await request(app)
.post('/login')
.send({
username: 'non-test user',password: 'non-test password',})
.expect(404)
})
我收到以下错误:无法读取 null 的属性 'JSON' 和 ReferenceError: db is not defined。 在路由器 http 请求函数(后端)中的 catch 块中打印的两个错误。 当我在每个请求中连接到数据库时,测试都通过了,但它导致了很多延迟,所以我将其更改为这种格式,其中我将 'db' 变量定义为全局变量并且只连接到数据库一次。 重要的是要注意,客户端-服务器通信在网站本身中运行良好,这些错误仅在 Jest 测试中出现。 感谢帮助!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)