From 9dfad9dca564a3340aa9901fc6e26e7b9cb0b11e Mon Sep 17 00:00:00 2001 From: Adrian Obelmejias Date: Wed, 16 Mar 2016 21:20:23 -0400 Subject: [PATCH] Add tests for authentication --- test/auth.spec.js | 51 +++++++++++++++++++++++++++++++++++++++++++++++ test/utils.js | 21 +++++++++++++++++-- 2 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 test/auth.spec.js diff --git a/test/auth.spec.js b/test/auth.spec.js new file mode 100644 index 0000000..fa9e5f8 --- /dev/null +++ b/test/auth.spec.js @@ -0,0 +1,51 @@ +import app from '../bin/server' +import supertest from 'supertest' +import { expect, should } from 'chai' +import { cleanDb, authUser } from './utils' + +should() +const request = supertest.agent(app.listen()) +const context = {} + +describe('Auth', () => { + before((done) => { + cleanDb() + authUser(request, (err, { user, token }) => { + if (err) { return done(err) } + + context.user = user + context.token = token + done() + }) + }) + + describe('POST /auth', () => { + it('should throw 401 if credentials are incorrect', (done) => { + request + .post('/auth') + .set('Accept', 'application/json') + .send({ username: 'supercoolname', password: 'wrongpassword' }) + .expect(401, done) + }) + + it('should auth user', (done) => { + request + .post('/auth') + .set('Accept', 'application/json') + .send({ username: 'test', password: 'pass' }) + .expect(200, (err, res) => { + if (err) { return done(err) } + + res.body.user.should.have.property('username') + res.body.user.username.should.equal('test') + expect(res.body.user.password).to.not.exist + expect(res.body.user.salt).to.not.exist + + context.user = res.body.user + context.token = res.body.token + + done() + }) + }) + }) +}) diff --git a/test/utils.js b/test/utils.js index 3ac5f12..f02445c 100644 --- a/test/utils.js +++ b/test/utils.js @@ -1,7 +1,24 @@ import mongoose from 'mongoose' -export function cleanDb () { +export function cleanDb() { for (const collection in mongoose.connection.collections) { - mongoose.connection.collections[collection].remove(); + if (mongoose.connection.collections.hasOwnProperty(collection)) { + mongoose.connection.collections[collection].remove() + } } } + +export function authUser(agent, callback) { + agent + .post('/users') + .set('Accept', 'application/json') + .send({ user: { username: 'test', password: 'pass' } }) + .end((err, res) => { + if (err) { return callback(err) } + + callback(null, { + user: res.body.user, + token: res.body.token + }) + }) +}