Skip to content
This repository has been archived by the owner on Nov 10, 2022. It is now read-only.

Commit

Permalink
test: add tests for server.ts
Browse files Browse the repository at this point in the history
also: refactor to remove dead code
  • Loading branch information
severo committed Jan 22, 2020
1 parent 555a8be commit e43a3da
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 578 deletions.
39 changes: 6 additions & 33 deletions src/server.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,49 +11,22 @@ const ioOptions = {
}

describe('/occupapp-beta', function() {
let clientSocket: SocketIOClient.Socket
// let socketIds: SocketIOClient.Socket['id'][]
let client: SocketIOClient.Socket

beforeEach(async function() {
socketServer.connect()
server.listen('3001')
clientSocket = ioc('http://localhost:3001/', ioOptions)
// socketIds = await Promise.all([
// new Promise(resolve => {
// clientSocket.on('connect', () => {
// resolve(clientSocket.id)
// })
// }),
// new Promise(resolve => {
// io.on('connection', (socket: SocketIOClient.Socket) => {
// resolve(socket.id)
// })
// }),
// ])
client = ioc('http://localhost:3001/occupapp-beta', ioOptions)
})
afterEach(function(done) {
clientSocket.disconnect()
client.disconnect()
server.close()

done()
})

// it('should use the same socket id clientside and serverside', function() {
// return expect(socketIds[0]).to.equal(socketIds[1])
// })

it('should update the user profile on "update-profile" event', function() {
// TODO: DOES NOT WORK AT ALL!!! NEVER EXECUTED
const name = 'test'
const color = '#888888'
clientSocket.emit('update-profile', { name, color }, (result: any) => {
expect(result).to.have.property('status')
expect(result.status).to.equal('success')
expect(result).to.have.property('data')
expect(result.data).to.have.property('name')
expect(result.data.name).to.equal(name)
expect(result.data).to.have.property('color')
expect(result.data.color).to.equal(color)
})
it('should connect socket', async () => {
await new Promise(resolve => client.on('connect', resolve))
expect(client.connected).to.be.true
})
})
97 changes: 0 additions & 97 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,106 +3,9 @@ import express from 'express'
import socketIo from 'socket.io'
import { Socket } from './socket.io/socket'

// const { RateLimiterMemory } = require('rate-limiter-flexible')

//
// const { Room } = require('./Room.js')
// const { User } = require('./User.js')

// TODO: add a public page that redirects to the GitHub repository
// app.use(express.static(__dirname + '/public'))

// const rateLimiter = new RateLimiterMemory({
// points: 2, // 2 points
// duration: 1 // per second
// })
//
// const chat = io.on('connection', socket => {
// socket.on('chat', data => {
// // console.log(`Message received: ${data}`)
// socket.broadcast.emit('chat', data)
// })
// })
//
// // state
// // TODO: it would be better to use the underlying state socket.io manages, but...
// // it seems to be difficult to access it (eg. getting the list of sockets for a
// // given room)
// // The current solution is to replicate this state, even if it implies having
// // ghosts users after some time, when a user has not disconnected properly.
// // current solution -> expiration date, and deleting these users
//
// const addRoom = (room) => {
// if (!rooms.has(room.name)) {
// rooms.set(room.name, room)
// }
// }
// const rooms = new Map()
// const uniqueRoomName = 'default room'
// const uniqueRoom = new Room(uniqueRoomName)
// addRoom(uniqueRoom)
//
// let urlQuerySpec = {}
//
// // const onUpdateUrlQuerySpec = socket => async (newUrlQuerySpec, ack) => {
// // console.log('new urlQuerySpec')
// // try {
// // await rateLimiter.consume(socket.id) // consume 1 point per event from IP
// // const guest = guests.get(socket.id)
// // if (guest !== undefined) {
// // touch(guest)
// // if (urlQuerySpec !== newUrlQuerySpec) {
// // // ?
// // urlQuerySpec = newUrlQuerySpec
// // socket.broadcast.emit('urlqueryspec', urlQuerySpec)
// // }
// // ack(urlQuerySpec)
// // }
// // console.log('OK')
// // } catch (rejRes) {
// // // no available points to consume
// // // emit error or warning message
// // socket.emit('blocked', { 'retry-ms': rejRes.msBeforeNext })
// // console.log('Blocked')
// // }
// // }
// const removeGuest = (room, socket) => {
// if (room.deleteUser(socket.id)) {
// emitProfilesList(room)
// }
// }
//
// const emitProfilesList = (room) => {
// // Clean the list, pruning expired users
// room.pruneExpiredUsers()
// // Send the list to everybody in the room
// io.of('/occupapp-beta').to(room.name).emit('list-profiles', room.profiles)
// }
//
// const updateProfile = (socketId: SocketIOClient.Socket['id'], profile, ack) => {
// // Validate payload
// const checkedProfile = UserProfile.checkProfile(profile)
// if (checkedProfile.error !== undefined) {
// ack({ status: 'error', error: checkedProfile.error })
// }
//
// // Create or update user
// // TODO: update the user profile independently from its room
// const currentUser = uniqueRoom.getUser(socketId)
// if (currentUser === undefined) {
// const user = new User(socketId, new UserProfile(checkedProfile))
// uniqueRoom.setUser(user)
// emitProfilesList(uniqueRoom)
// ack({ status: 'success', data: user.profile })
// } else {
// currentUser.profile.updateWith(checkProfile)
// uniqueRoom.setUser(currentUser)
// // TODO: only notify everybody if something has changed in the profile
// emitProfilesList(uniqueRoom)
// ack({ status: 'success', data: currentUser.profile })
// }
// }

const port: number = +process.env.PORT || 3000
const app: express.Application = express()
const server = http.createServer(<any>app)
Expand Down
7 changes: 5 additions & 2 deletions src/socket.io/socket.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import {
import { StateEvent, UsersListEvent } from '../domain/events/toclient'
import { ExportedUser } from '../domain'

const socketUrl: string = 'http://localhost:5000'
const PORT: number = 5000
const socketUrl: string = `http://localhost:${PORT}`
const options: SocketIOClient.ConnectOpts = {
transports: ['websocket'],
forceNew: true,
Expand All @@ -37,10 +38,12 @@ describe('Server', () => {
const NEW_CLIENT_IDX = 2

beforeEach(() => {
server = io().listen(5000)
server = io()
mockLogger = new MockLogger()
socket = new Socket(server, mockLogger)
socket.connect()
server.listen(PORT)

client = ioClient.connect(socketUrl + '/occupapp-beta', options)
passiveClient = ioClient.connect(socketUrl + '/occupapp-beta', options)
})
Expand Down
Loading

0 comments on commit e43a3da

Please sign in to comment.