Skip to content

Instantly share code, notes, and snippets.

@francisbrito
Created January 18, 2016 14:07
Show Gist options
  • Save francisbrito/74b8261badf42600ee1f to your computer and use it in GitHub Desktop.
Save francisbrito/74b8261badf42600ee1f to your computer and use it in GitHub Desktop.
Mongorito test example.
const test = require('blue-tape');
const Promise = require('bluebird');
const mongorito = require('mongorito');
/**
* A simple Mongorito Model. Nothing special.
*/
const Post = require('./models').Post;
/**
* Some aliases for better readability
*/
const afterAll = beforeAll = test;
/**
* Random data used to populate database.
*/
const fixtures = [
{title: 'foo'},
{title: 'bar'},
{title: 'baz'},
{title: 'qnx'},
{title: 'sabrina is cool'},
];
/**
* Due to Mongorito's design you may connect *only* once and keep that connection
* alive for the rest of the tests.
*
* **NOTE:** I'm using bluetape instead of tape, which means that if a promise is being returned
* there's no need for `t.end`-ing or `t.plan`-ning tests.
*/
beforeAll('connect to database', () => {
return connect();
});
beforeAll('load fixtures', (assert) => {
// Just store all fixtures in the database as posts.
return Promise.all(
fixtures
.map( f => new Post(f) )
.map( p => p.save() )
);
});
test('query my models', (assert) => {
return Post
.find()
.then( assertICanQueryPosts(assert) )
});
afterAll('unload fixtures', () => {
return Post.drop();
})
afterAll('disconnect from database', () => {
return disconnect();
});
function assertICanQueryPosts(assert) {
return (posts) => {
assert.ok(posts, 'should have posts');
assert.ok(posts.length, 'should be an array');
assert.equal(posts.length, fixtures.length, `should have ${fixtures.length} items`);
};
}
function connect() {
return mongorito.connect('localhost/test');
}
function disconnect() {
return mongorito.disconnect();
}
const mongorito = require('mongorito');
module.exports.Post = mongorito.Model.extend({
collection: 'posts',
});
{
"name": "mongorito-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "blue-tape index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"blue-tape": "^0.1.11",
"bluebird": "^3.1.1",
"mongorito": "git+https://github.com/vdemedes/mongorito.git"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment