Add tests for authentication

This commit is contained in:
Adrian Obelmejias
2016-03-16 21:20:23 -04:00
parent 0f3384eb57
commit 9dfad9dca5
2 changed files with 70 additions and 2 deletions
+51
View File
@@ -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()
})
})
})
})
+19 -2
View File
@@ -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
})
})
}