Skip to content

Instantly share code, notes, and snippets.

@nawarian
Created September 27, 2022 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nawarian/604c4c5ee5a09aef71ee7bd6989142a1 to your computer and use it in GitHub Desktop.
Save nawarian/604c4c5ee5a09aef71ee7bd6989142a1 to your computer and use it in GitHub Desktop.
TDL: MongoDB com mongoose e Jest
MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD=root
# Iniciar banco de dados MongoDB via `docker`
docker run -it --rm --env-file .env -p27017:27017 mongo:latest
# Rodar suite de testes Jest
npm run test -- --watchAll
const mongoose = require('mongoose')
const MONGODB_DSN = 'mongodb://root:root@localhost:27017'
test('Conexão com MongoDB', async () => {
const promise = mongoose.connect(MONGODB_DSN)
await expect(promise).resolves.toBeInstanceOf(mongoose.Mongoose)
})
const artigoSchema = new mongoose.Schema({
titulo: String,
url: String,
})
// 'Artigo' vai ser tratado como uma classe de agora em diante
const Artigo = mongoose.model('artigos', artigoSchema)
test('Inserção no MongoDB', async () => {
// Nós já vimos que a linha abaixo conecta ao DB
await mongoose.connect(MONGODB_DSN)
// Criamos um artigo novo
const tutorial_mongodb = new Artigo({
titulo: 'Como conectar com mongodb no node.js com TDD',
url: 'https://codamos.com.br/como-conectar-mongodb-nodejs-tdd',
})
await tutorial_mongodb.save()
// 'tutorial_mongodb' agora deverá ter um campo '_id'
expect(tutorial_mongodb._id).toBeInstanceOf(mongoose.Types.ObjectId)
})
test('Listar todos documentos no MongoDB', async () => {
await mongoose.connect(MONGODB_DSN)
const artigoSchema = new mongoose.Schema({
titulo: String,
url: String,
})
const artigosEncontrados = await Artigo.find()
expect(artigosEncontrados.length).toBeGreaterThan(0)
})
{
"name": "tdl-mongodb-com-mongoose-e-jest",
"type": "module",
"dependencies": {
"mongoose": "^6.6.2"
},
"devDependencies": {
"jest": "^29.0.3"
},
"scripts": {
"test": "jest"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment