forked from koa-boilerplate

This commit is contained in:
Chris Troutner
2019-01-20 18:12:23 -08:00
commit 44b519bfcb
30 changed files with 1577 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
The files in this directory are named so as to control the order in which
the files are executed by mocha. a01... runs first. The order is important,
as some tests downstream depend on tests upstream.
+106
View File
@@ -0,0 +1,106 @@
const app = require('../bin/server')
// const supertest = require('supertest')
// const expect = require('chai').expect
const should = require('chai').should
// const cleanDb = require('./utils').cleanDb
// const authUser = require('./utils').authUser
const utils = require('./utils')
const rp = require('request-promise')
const assert = require('chai').assert
should()
// const request = supertest.agent(app.listen())
const context = {}
const LOCALHOST = 'http://localhost:5000'
describe('Auth', () => {
before(async () => {
await app.startServer()
utils.cleanDb()
/*
authUser(request, (err, { user, token }) => {
if (err) { return done(err) }
context.user = user
context.token = token
done()
})
*/
const userObj = {
username: 'test',
password: 'pass'
}
const testUser = await utils.createUser(userObj)
context.user = testUser.user
context.token = testUser.token
})
describe('POST /auth', () => {
it('should throw 401 if credentials are incorrect', async () => {
try {
const options = {
method: 'POST',
uri: `${LOCALHOST}/auth`,
resolveWithFullResponse: true,
json: true,
body: {
username: 'test',
password: 'wrongpassword'
}
}
let result = await rp(options)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
console.log(`result stringified: ${JSON.stringify(result, null, 2)}`)
assert(false, 'Unexpected result')
} catch (err) {
if (err.statusCode === 422) {
assert(err.statusCode === 422, 'Error code 422 expected.')
} else if (err.statusCode === 401) {
assert(err.statusCode === 401, 'Error code 401 expected.')
} else {
console.error('Error: ', err)
console.log('Error stringified: ' + JSON.stringify(err, null, 2))
throw err
}
}
})
it('should auth user', async () => {
try {
const options = {
method: 'POST',
uri: `${LOCALHOST}/auth`,
resolveWithFullResponse: true,
json: true,
body: {
username: 'test',
password: 'pass'
}
}
let result = await rp(options)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert(result.statusCode === 200, 'Status Code 200 expected.')
assert(result.body.user.username === 'test', 'Username of test expected')
assert(result.body.user.password === undefined, 'Password expected to be omited')
} catch (err) {
console.log('Error authenticating test user: ' + JSON.stringify(err, null, 2))
throw err
}
})
})
})
+403
View File
@@ -0,0 +1,403 @@
const expect = require('chai').expect
const should = require('chai').should
const utils = require('./utils')
const rp = require('request-promise')
const assert = require('chai').assert
const util = require('util')
util.inspect.defaultOptions = { depth: 1 }
const LOCALHOST = 'http://localhost:5000'
should()
const context = {}
describe('Users', () => {
before(async () => {
utils.cleanDb()
})
describe('POST /users', () => {
it('should reject signup when data is incomplete', async () => {
try {
const options = {
method: 'POST',
uri: `${LOCALHOST}/users`,
resolveWithFullResponse: true,
json: true,
body: {
username: 'supercoolname'
}
}
let result = await rp(options)
console.log(`result stringified: ${JSON.stringify(result, null, 2)}`)
assert(false, 'Unexpected result')
} catch (err) {
if (err.statusCode === 422) {
assert(err.statusCode === 422, 'Error code 422 expected.')
} else if (err.statusCode === 401) {
assert(err.statusCode === 401, 'Error code 401 expected.')
} else {
console.error('Error: ', err)
console.log('Error stringified: ' + JSON.stringify(err, null, 2))
throw err
}
}
})
it('should sign up', async () => {
try {
const options = {
method: 'POST',
uri: `${LOCALHOST}/users`,
resolveWithFullResponse: true,
json: true,
body: {
user: { username: 'supercoolname', password: 'supersecretpassword' }
}
}
let result = await rp(options)
result.body.user.should.have.property('username')
result.body.user.username.should.equal('supercoolname')
expect(result.body.user.password).to.not.exist
context.user = result.body.user
context.token = result.body.token
} catch (err) {
console.log(
'Error authenticating test user: ' + JSON.stringify(err, null, 2)
)
throw err
}
})
})
describe('GET /users', () => {
it('should not fetch users if the authorization header is missing', async () => {
try {
const options = {
method: 'GET',
uri: `${LOCALHOST}/users`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json'
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 401)
}
})
it('should not fetch users if the authorization header is missing the scheme', async () => {
try {
const options = {
method: 'GET',
uri: `${LOCALHOST}/users`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: '1'
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 401)
}
})
it('should not fetch users if the authorization header has invalid scheme', async () => {
const { token } = context
try {
const options = {
method: 'GET',
uri: `${LOCALHOST}/users`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Unknown ${token}`
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 401)
}
})
it('should not fetch users if token is invalid', async () => {
try {
const options = {
method: 'GET',
uri: `${LOCALHOST}/users`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer 1`
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 401)
}
})
it('should fetch all users', async () => {
const { token } = context
const options = {
method: 'GET',
uri: `${LOCALHOST}/users`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
const result = await rp(options)
const users = result.body.users
// console.log(`users: ${util.inspect(users)}`)
assert.hasAnyKeys(users[0], ['type', '_id', 'username'])
assert.equal(users.length, 1)
})
})
describe('GET /users/:id', () => {
it('should not fetch user if token is invalid', async () => {
try {
const options = {
method: 'GET',
uri: `${LOCALHOST}/users/1`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer 1`
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 401)
}
})
it("should throw 404 if user doesn't exist", async () => {
const { token } = context
try {
const options = {
method: 'GET',
uri: `${LOCALHOST}/users/1`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 404)
}
})
it('should fetch user', async () => {
const {
user: { _id },
token
} = context
const options = {
method: 'GET',
uri: `${LOCALHOST}/users/${_id}`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
const result = await rp(options)
const user = result.body.user
// console.log(`user: ${util.inspect(user)}`)
assert.hasAnyKeys(user, ['type', '_id', 'username'])
assert.equal(user._id, _id)
assert.notProperty(
user,
'password',
'Password property should not be returned'
)
})
})
describe('PUT /users/:id', () => {
it('should not update user if token is invalid', async () => {
try {
const options = {
method: 'PUT',
uri: `${LOCALHOST}/users/1`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer 1`
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 401)
}
})
it("should throw 404 if user doesn't exist", async () => {
const { token } = context
try {
const options = {
method: 'PUT',
uri: `${LOCALHOST}/users/1`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 404)
}
})
it('should update user', async () => {
const {
user: { _id },
token
} = context
const options = {
method: 'PUT',
uri: `${LOCALHOST}/users/${_id}`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
},
body: {
user: { username: 'updatedcoolname' }
}
}
const result = await rp(options)
const user = result.body.user
// console.log(`user: ${util.inspect(user)}`)
assert.hasAnyKeys(user, ['type', '_id', 'username'])
assert.equal(user._id, _id)
assert.notProperty(
user,
'password',
'Password property should not be returned'
)
assert.equal(user.username, 'updatedcoolname')
})
})
describe('DELETE /users/:id', () => {
it('should not delete user if token is invalid', async () => {
try {
const options = {
method: 'DELETE',
uri: `${LOCALHOST}/users/1`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer 1`
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 401)
}
})
it('should throw 404 if user doesn\'t exist', async () => {
const { token } = context
try {
const options = {
method: 'DELETE',
uri: `${LOCALHOST}/users/1`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
await rp(options)
assert.equal(true, false, 'Unexpected behavior')
} catch (err) {
assert.equal(err.statusCode, 404)
}
})
it('should delete user', async () => {
const {
user: { _id },
token
} = context
const options = {
method: 'DELETE',
uri: `${LOCALHOST}/users/${_id}`,
resolveWithFullResponse: true,
json: true,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
}
}
const result = await rp(options)
// console.log(`result: ${util.inspect(result.body)}`)
assert.equal(result.body.success, true)
})
})
})
+68
View File
@@ -0,0 +1,68 @@
const mongoose = require('mongoose')
const rp = require('request-promise')
const LOCALHOST = 'http://localhost:5000'
// Remove all collections from the DB.
function cleanDb () {
for (const collection in mongoose.connection.collections) {
if (mongoose.connection.collections.hasOwnProperty(collection)) {
mongoose.connection.collections[collection].deleteMany()
}
}
}
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
})
})
}
// This function is used to create new users.
// userObj = {
// username,
// password
// }
async function createUser (userObj) {
try {
const options = {
method: 'POST',
uri: `${LOCALHOST}/users`,
resolveWithFullResponse: true,
json: true,
body: {
user: {
username: userObj.username,
password: userObj.password
}
}
}
let result = await rp(options)
const retObj = {
user: result.body.user,
token: result.body.token
}
return retObj
} catch (err) {
console.log('Error in utils.js/createUser(): ' + JSON.stringify(err, null, 2))
throw err
}
}
module.exports = {
cleanDb,
authUser,
createUser
}