테스트를 위한 인메모리 MongoDB?
내 노드에 대한 통합 및 시스템 테스트를 작성하고 있습니다.MongoDB 데이터베이스를 사용하는 JS 응용 프로그램입니다.제가 사용하는 테스트 프레임워크는 모카와 슈퍼테스트입니다.MongoDB를 테스트에만 사용할 수 있는 인메모리 데이터베이스로 설정할 수 있습니까? 테스트가 완료되면 모든 컬렉션과 문서를 삭제합니다.
mongodb-memory-server를 사용하여 이 작업을 수행할 수 있습니다.패키지는 mongod 바이너리를 홈 디렉토리로 다운로드하고 필요에 따라 메모리 백업 MondoDB 인스턴스를 인스턴스화합니다.각 테스트 파일에 대해 새 서버를 스핀업할 수 있습니다. 즉, 모든 서버를 병렬로 실행할 수 있습니다.
just 및 네이티브 mongodb 드라이버를 사용하는 독자에게는 이 클래스가 유용할 수 있습니다.
const { MongoClient } = require('mongodb');
const { MongoMemoryServer } = require('mongodb-memory-server');
// Extend the default timeout so MongoDB binaries can download
jest.setTimeout(60000);
// List your collection names here
const COLLECTIONS = [];
class DBManager {
constructor() {
this.db = null;
this.server = new MongoMemoryServer();
this.connection = null;
}
async start() {
const url = await this.server.getUri();
this.connection = await MongoClient.connect(url, { useNewUrlParser: true });
this.db = this.connection.db(await this.server.getDbName());
}
stop() {
this.connection.close();
return this.server.stop();
}
cleanup() {
return Promise.all(COLLECTIONS.map(c => this.db.collection(c).remove({})));
}
}
module.exports = DBManager;
그런 다음 각 테스트 파일에서 다음을 수행할 수 있습니다.
const dbman = new DBManager();
afterAll(() => dbman.stop());
beforeAll(() => dbman.start());
afterEach(() => dbman.cleanup());
저는 이 접근 방식이 다른 테스트 프레임워크에서도 유사할 수 있다고 생각합니다.
mongodb-memory-server 사용을 권장합니다.
프로젝트 전체에 걸쳐 공유되는 DB 파일이 있어서 테스트 가능해야 합니다.
//db.js
import mongoose from 'mongoose';
import bluebird from 'bluebird';
module.exports = {
mongoose,
init: () => {
mongoose.Promise = bluebird;
},
connect: async database => {
try {
const conn = await mongoose.connect(
database,
{ useNewUrlParser: true }
);
//eslint-disable-next-line
console.log(`MongoDb Connected on: ${database}`);
return conn;
} catch (err) {
//eslint-disable-next-line
console.log('Error to connect on mongo', err);
}
},
disconnect: async () => await mongoose.connection.close()
};
테스트에 사용하기 위해 test-helper.js 파일을 만들었습니다.
'use strict';
import MongodbMemoryServer from 'mongodb-memory-server';
import db from '../src/db';
const server = new MongodbMemoryServer();
const createDB = async () => {
try {
const url = await server.getConnectionString();
db.connect(url);
} catch (err) {
throw err;
}
};
const destroyDB = () => {
db.disconnect();
};
module.exports = {
createDB,
destroyDB
};
}
따라서 제 테스트는 항상 DB 생성 및 파기 전후에 수행됩니다.
import { createDB, destroyDB } from '../test-helper';
before(() => {
createDB();
});
after(() => {
destroyDB();
});
도움이 되길 바랍니다.
제가 사용하고 있는 프로젝트: https://github.com/abdalla/node-auth
언급URL : https://stackoverflow.com/questions/13607732/in-memory-mongodb-for-test
'codememo' 카테고리의 다른 글
| Oracle 문제의 매개 변수화된 쿼리 (0) | 2023.06.27 |
|---|---|
| 분류법 슬러그가 포함된 Wordpress 사용자 지정 유형 퍼멀링크 (0) | 2023.06.27 |
| 일반 프로그램이 보통 0x8000에서 시작하는 이유는 무엇입니까? (0) | 2023.06.27 |
| Firebase 충돌 분석:누락된 dSYM을 업로드하여 1개 버전의 충돌을 확인합니다. (iOS) (0) | 2023.06.27 |
| "while" 루프와 "do while" 루프의 차이 (0) | 2023.06.27 |