Jest.js MongoParseError:URI没有hostname、domain name和tld,只有在测试方法时才有

bejyjqdl  于 2023-11-15  发布在  Jest
关注(0)|答案(1)|浏览(116)

我正在尝试测试我的MongoDB库。我想验证一个变量是否是我的库的示例,以及该方法是否被正确调用。我正在使用jest进行测试。

import { MongoLib } from '../index'

let database: any

beforeAll(() => {
  database = new MongoLib({
    hostname: 'localhost',
    database: 'test',
    password: encodeURI('password'),
    username: 'anothertest'
  })
})

afterAll(() => {
 database = null
})

describe('Initializing class', () => {
  test('isInstanceOf', () => {
    expect(database).toBeInstanceOf(MongoLib)
  })
})

describe('Methods#ToBeThruty', () => {
  test('getAllToBeThruty', async () => {
    try {
      const users = await database.getAll('users')
      expect(users).toBeTruthy()
    } catch (error) {
      console.error(error)
    }
  })
  test('getToBeThruty', async () => {
    try {
      const user = await database.get('users', '60e13de94a37e1c6d0174749')
      expect(user).toBeTruthy()
    } catch (error) {
      console.error(error)
    }
  })
  test('createToBeThruty', async () => {
      try {
      const user = await database.create('users', { user: 'hello', email: 'world' })
      expect(user).toBeTruthy()
    } catch (error) {
      console.error(error)
    }
  })
  test('updateToBeThruty', async () => {
    try {
      const user = await database.update('users', '60e13de94a37e1c6d0174749', { user: 'world', email: 'hello' })
      expect(user).toBeTruthy()
    } catch (error) {
      console.error(error)
    }
  })

  test('replaceToBeThruty', async () => {
    try {
      const user = await database.replace('users', '60e13de94a37e1c6d0174749', { user: 'world', email: 'hello' })
      expect(user).toBeTruthy()
    } catch (error) {
      console.error(error)
    }
  })

  test('deleteToBeThruty', async () => {
    try {
      const user = await database.delete('users', '60e13de94a37e1c6d0174749')
      expect(user).toBeTruthy()
    } catch (error) {
      console.error(error)
    }
  })
})

字符串
测试通过了,但在那之后,我得到了这个错误:
MongoParseError:URI在parseSrvConnectionString中没有主机名、域名和TLD(/Users/diesanromero/Documents/KemusCorp/OpenSource/mongodb- crud/node_modules/mongodb/lib/core/uri_parser.js:51:21)
在MongoLib.Object..MongoLib.connect(/Users/diesanromero/Documents/KemusCorp/OpenSource/mongodb- crud/src/index.ts:25:29)在MongoLib.(/Users/diesanromero/Documents/KemusCorp/OpenSource/mongodb- crud/src/index.ts:40:17)
MongoLib的代码如下:

import { MongoClient, ObjectId } from 'mongodb'
import Settigns from "./settings"

export class MongoLib {
  private credentials: string
  private database: string
  private host: string
  private options: object
  private client: MongoClient
  private url: string
  private static connection: any

  constructor(settings: Settigns) {
    this.credentials = `${settings.username}:${settings.password}`
    this.host = `${settings.hostname}:${settings.port}`
    this.database = settings.database

    this.url = `mongodb+srv://${this.credentials}@${this.host}/${settings.database}?retryWrites=true&w=majority`
    this.options = { useUnifiedTopology: true }
    this.client = new MongoClient(this.url, this.options)
  }

  private connect () {
    if (!MongoLib.connection) {
      MongoLib.connection = new Promise((resolve, reject) => {
        this.client.connect((error: Error) => {
          if (error) reject(error)
          else {
            resolve(this.client.db(this.database))
            console.log('Connected successfully to MongoDB.')
          }
        })
      })
    }

    return MongoLib.connection
  }
  
  public async getAll (collection: string, query?: object) {
    return this.connect()
      .then((db: any) => {
        return db.collection(collection).find(query).toArray()
      })
  }

  public async get (collection: string, id: string) {
    return this.connect()
      .then((db:any) => {
        return db.collection(collection).findOne({ _id: new ObjectId(id) })
      })
  }

  public async create (collection: string, data: object) {
    return this.connect()
      .then((db: any) => {
        return db.collection(collection).insertOne(data)
      })
      .then(() => 'Data inserted')
  }

  public async update (collection: string, id: string, data: object) {
    return this.connect()
      .then((db: any) => {
        return db.collection(collection).updateOne({ _id: new ObjectId(id) }, { $set: data }, { upsert: true })
      })
      .then(() => 'Data updated')
  }

  public async replace (collection: string, id: string, data: object) {
    return this.connect()
      .then((db: any) => {
        return db.collection(collection).replaceOne({ _id: new ObjectId(id) }, data, { upsert: true })
      })
      .then(() => 'Data replaced')
  }

  public async delete (collection: string, id: string) {
    return this.connect()
      .then((db: any) => {
        return db.collection(collection).deleteOne({ _id: new ObjectId(id) })
      })
      .then(() => 'Data deleted')
  }
}


请记住,settings.js是一个带有基本配置的导出接口。

yc0p9oo0

yc0p9oo01#

确保连接字符串在开头有以下内容。

  1. mongodb+srv://
  2. mongodb://
    其次,检查您的密码是否符合以下列表,然后将其从以下enter image description here中替换
    第三种方法,为我工作是创建一个新的用户与密码没有任何特殊字符。

相关问题